Many times we need to do some things like releasing resources when the program exits, but there are many ways to exit the program, such as the main () function ends, the program ends with exit (), The user terminates the program by CTRL + C or ctrl+break, and so On. therefore, it is necessary to have a method that is independent of the program exit mode to process the program Exit. The method is to use the Atexit () function to register the function to be called when the program terminates normally.
The argument to the Atexit () function is a function pointer that points to a function that has no parameters and no return Value.
The function prototypes for atexit () are:
#include <cstdlib>
intatexit(void(*func)(void));
Atexit () returns zero on success and nonzero on Failure.
You can register at least 32 processing functions in a program (you can at least 32 times, which depends on your compiler), and the order of the handlers is the reverse of the order in which they were registered, that is, the last call that was first registered, and the last one that was first Registered.
There is a need to correct a lot of people on the web, they say atexit () can be called up to 32 times, but in fact atexit can be called at least 32 Times.
function Description: atexit () is used to set a function that is called before the program ends NORMALLY. When a program calls exit () or returns from main, the function specified by the parameter functions is called first, and then the program is actually terminated by exit ().
Return value: returns 0 if execution succeeds, otherwise returns-1, the reason for the failure is stored in errno.
Example
#include <stdlib.h>
void My_exit (void)
{
printf ("before Exit ()!\n");
}
Main ()
{
Atexit (my_exit);
Exit (0);
}
Perform:
Before Exit ()!
Transferred from: http://www.51testing.com/html/38/225738-235458.html
Http://c.biancheng.net/cpp/html/270.html
Description of Function--atexit () function executed at the end of A/C + + program