The atexit function is used to register a function to be called when the program ends. The objective of such function is usually to clean up and free resources that have been used by the program, such as files, memory blocks, and network connections.

The atexit function can register more than one function to be executed. In that case, atexit adds the function to the front of a "last-in first-out" list. This means that the functions are called in the reverse order in which they were added.

The atexit function requires only one argument. The argument specifies the function to be called at the exit of the program. The function must have a signature of void function(void), since this is how it will be called by atexit.

The return value of the atexit function is int. This value is zero whenever the function is successful, and -1 if there is any error. There might be an error if atexit cannot allocate more space for its internal list when a new function is added. Thus, it is always wise to check if the function returned -1.

The following code shows an example of atexit in use:

#include <stdlib.h>
#include        <stdio.h>

void do_at_exit()
   printf("do_at_exit was called\n");

void do_at_exit_2()
   printf("second do_at_exit function called\n");

int main()
        printf("beginning execution\n");
        return 0;

Article created on 2008-08-19 21:40:10

Post a comment