19.1 Terminate-and-Stay-Resident Programs

DOS maintains a pointer to the beginning of unused memory. Programs load into memory at this position. They terminate execution by returning control to DOS. Normally, the pointer remains unchanged, allowing DOS to reuse memory when loading other programs.

A terminating program can, however, prevent other programs from loading on top of it. It does this by returning to DOS through the terminate-and-stay-resident function, which resets the free-memory pointer to a higher position. This leaves the program resident in a protected block of memory, even though it is no longer running.

The terminate-and-stay-resident function (Function 31h) is one of the DOS services invoked through Interrupt 21h. The following fragment shows how a TSR program terminates using Function 31h and remains resident in a 1000h-byte block of memory:

mov ah, 31h ; Request DOS Function 31h

mov al, err ; Set return code

mov dx, 100h ; Reserve 100h paragraphs

; (1000h bytes)

int 21h ; Terminate-and-stay-resident

NOTE:

In current versions of DOS, Interrupt 27h also provides a terminate-and-stay-resident service. However, Microsoft cannot guarantee future support for Interrupt 27h and does not recommend its use.