atexit -- Record Program Termination Function

Format

#include <stdlib.h>
int atexit(void (*func)(void));

Language Level: ANSI, POSIX, XPG4
atexit records a function, pointed to by func, that the system calls at normal program termination. The functions are executed in a last-in, first-out order.

Note: Although you can register more than 32 functions (ANSI limit), for portability reasons, you should not do so.

Functions registered in an image will be executed when that image terminates. Assume, for example, that your application has an .exe and a .dll. Functions registered from the .exe file are executed on program termination. The function registered calling atexit within the DLL will be executed when this DLL is unloaded.

Notes:

  1. If the DLL is loaded statically (that is, the application was linked to the corresponding import library), the DLL is unloaded at the program termination. In other words, all the functions registered in both .exe and .dll will be executed without interruption. If the DLL is loaded dynamically (using DosLoadModule on OS/2 or LoadLibrary on Windows), then the functions registered from the DLL will be executed when you call the corresponding DosFreeModule for OS/2 or FreeLibrary for Windows.
  2. Do not call atexit from one image to register a function from another image because when the .exe or .dll file terminates, the function will not exist at the time that it is called.

Return Value
atexit returns 0 if it is successful, and nonzero if it fails.

Example
This example uses atexit to call the function goodbye at program termination.

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   void goodbye(void);
   int rc;
   rc = atexit(goodbye);
   if (rc != 0)
      perror("Error in atexit");
   exit(0);
}
void goodbye(void)
   /* This function is called at normal program termination */
{
   printf("The function goodbye was called at program termination\n");
   /*******************************************************************
      The output should be:
      The function goodbye was called at program termination
   *******************************************************************/
}


exit -- End Program
_exit -- End Process
_onexit -- Record Termination Funct ion
signal -- Handle Interrupt Signals
<stdlib.h>