INT 21h Input and Output in Emu8086

Underneath the friendly macros in emu8086.inc sits a plain mechanism: interrupt 21h, the DOS service call. You set a function number in AH, set up any other registers the function needs, and execute INT 21h. This tutorial covers the four functions a beginner program uses most. Emu8086 setup is in the install guide.

The four functions

  • Function 09h: print a string. DX points at the string, which must end with $.
  • Function 02h: print one character. DL holds the character.
  • Function 01h: read one key, with echo. The character comes back in AL.
  • Function 4Ch: exit a .EXE program with a return code in AL. A .COM program normally just uses RET instead.

A complete program: ask, read, echo

The program below prints a prompt, waits for a keypress, then prints the key on a new line. It uses no macros, so it needs no include line. Watch the order of the newline: the carriage return (13) and line feed (10) are printed as two separate characters through function 02h, before the echoed character is printed.

ORG 100h

LEA DX, prompt
MOV AH, 09h
INT 21h

MOV AH, 01h
INT 21h
MOV BL, AL

MOV AH, 02h
MOV DL, 13
INT 21h
MOV DL, 10
INT 21h

MOV DL, BL
INT 21h
RET

prompt DB 'Press a key: $'

What you should see

After you press a key, say k, the emulator window should show the prompt, the echoed key, and then the same key again on the next line. The first appearance is the echo from function 01h; the second is your own function 02h print. If the key appears only once, the echo may have been consumed differently by your emulator settings; the important check is that the character on the new line matches the key you pressed.

Why the key is saved in BL

Function 01h returns the character in AL, but the very next function call needs AH set to 02h, which overwrites the high half of AX. Saving AL into BL first protects the character. This is the same register-preservation idea as the stack tutorial, done here with a spare register instead of the stack. Forgetting to save it is the classic INT 21h beginner bug: the printed character comes out as something unrelated to the key pressed.

Choosing macros or raw INT 21h

Macros are shorter to write and easier to read. Raw INT 21h calls show what is really happening and work in programs that do not include emu8086.inc. A good rule is to learn both: write your first programs with macros, then rewrite one of them with raw services, as in the Hello World comparison in the first tutorial, so you understand what the macros were doing for you.

Next steps

Next, step debugging shows how to watch AH and AL change at each service call, and .COM vs .EXE explains where function 4Ch fits. The opcode reference covers INT itself, and the home page links the series.

Similar Posts