Install a function to be executed at a program's exit.
#include <stdlib.h> int atexit(void (*func)(void));
func
The function to execute at exit.
The atexit() function adds the function pointed to by func to a list. When exit() is called, each function on the list is called in the reverse order in which they were installed with atexit(). After all the functions on the list have been called, exit() terminates the program.
The stdio.h library, for example, installs its own exit function using atexit(). This function flushes all buffers and closes all open streams.
atexit() returns a zero when it succeeds in installing a new exit function and returns a nonzero value when it fails.
#include <stdlib.h> #include <stdio.h> /* Prototypes */ void prompt(void); void first(void); void second(void); void third(void); int main(void) { atexit(first); atexit(second); atexit(third); printf("exiting program\n\n"); return 0; } void prompt(void) { int c; printf("Press Return."); c = getchar(); } void first(void) { printf("First exit function.\n"); prompt(); } void second(void) { printf("Second exit function.\n"); prompt(); } void third(void) { printf("Third exit function.\n"); prompt(); } Output: Third exit function. Press Return. Second exit function. Press Return. First exit function. Press Return.