There are often multiple exit procedures in the program, and some cleaning work should be performed when the program exits. If there is a method that can provide no relation to the program exit method to process the program exit, it is necessary to simplify programming. Atexit () is such a method.
The atexit () statement is as follows:
extern "C" int atexit (void (*func)(void)) noexcept;extern "C++" int atexit (void (*func)(void)) noexcept;
The atexit parameter is a non-parameter function pointer, which is automatically executed when the program Exits normally.
There are eight ways to terminate the process, the first five of which are normal termination, they are
1: return from main
2: Call exit
3: Call _ exit or _ exit
4: The last thread returns from its startup routine
5: The last thread calls pthread_exit.
There are three types of exceptional termination:
6: call abort
7. receive a signal and terminate
8: The last thread responds to the cancellation request.
Atexit supports registration of up to 32 functions (different platforms may be different, but at least 32 functions). These functions are called in reverse order when the program exits. The same function can be registered multiple times.
If the registered function is successfully executed, a non-zero value is returned; otherwise, 0 is returned.
Below is a small example:
#include <stdio.h> /* puts */#include <stdlib.h> /* atexit */void fnExit1 (void){ puts ("Exit function 1.");}void fnExit2 (void){ puts ("Exit function 2.");}int main (){ atexit (fnExit1); atexit (fnExit1); atexit (fnExit2); puts ("Main function."); return 0;}
The running result is as follows:
This article is also published at: Hey, stay tuned