The initialization routine prepares the terminate-and-stay-resident program to be used by other programs or to service interrupts generated by a device. The initialization routine must do the following:
Make sure the TSR is not already loaded.
Install the interrupt handler (or handlers).
Free unneeded resources.
Call Keep Program (Interrupt 21h Function 31h).
Unless a TSR is designed to be loaded more than once, it should safeguard against the user's starting it multiple times. The TSR can do this by using Multiplex Interrupt (Interrupt 2Fh) and a custom interrupt handler. An MS-DOS TSR, such as PRINT.EXE, uses this technique. In general, each time it starts, the TSR issues Interrupt 2Fh, supplying an identifier unique to the TSR. If the interrupt returns a reply, a copy of the TSR has already been loaded. Otherwise, the TSR must install a custom handler that replies to all subsequent calls to the TSR.
The TSR must install its interrupt handlers by using Set Interrupt Vector (Interrupt 21h Function 25h). This function copies the address of the interrupt handler to the interrupt table. If a program or device issues the corresponding interrupt, control passes to the interrupt handler. Before installing the interrupt handler, the TSR should also use Get Interrupt Vector (Interrupt 21h Function 35h) to retrieve the address of the current handler so that it can be restored if the TSR is removed from memory.
Before calling Keep Program, the initialization routine should do the following:
Close all unneeded files, including standard devices.
Free the environment block if it is not needed.
Free all memory not needed to support the interrupt handler.
When it calls Keep Program, the routine should specify the smallest possible amount of program memory to retain. In particular, the code and data for the initialization routine should be at the end of the TSR, to ensure that they are freed by Keep Program.