The difference between exit and atexit is explained in detail

  • 2020-04-02 01:30:30
  • OfStack

1. Exit () function
Function declaration:
Void exit (int state);
The exit() function is used to terminate the program at any time while the program is running. The parameter state of exit is returned to the operating system. The exit function is also implicitly called when the main function ends. The exit function runtime first executes the functions registered by the atexit() function, then does some cleanup of its own, flushing all output streams, closing all open streams, and closing temporary files created by the standard I/O function tmpfile().

Atexit () function
Function declaration:
Int atexit (void func (*) (void));  
Many times we need to exit the program do some operations such as release resources, but the program exits, there are many ways of, such as the main () function to run over, somewhere in the program with the exit () the end of the program, the user through a Ctrl + C or Ctrl + break operation to terminate the program, etc., so you need to have a has nothing to do with the program exits mode method to carry out the necessary processing when the program exits. 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 to a function that takes no arguments and returns no value. The function prototype of atexit() is: int atexit(void (*)(void));

Up to 32 handlers can be registered in a program with atexit(), which is called in the reverse order of its registration, that is, the last call first registered and the first call last registered.

Here is an example of the code:


#include <stdlib.h> //The header file stdlib.h that must be included to use the atexit() function
#include <iostream.h>
void terminateTest()
{
    cout<<" The program is ending ..."<<endl;
}
int main(void)
{
    //Register the exit handler
    atexit(terminateTest);
    cout<<"the end of main()"<<endl;
    return 0;
}

The running result of the program is:
The end of the main ()
The process is ending...

These functions are called after main ends. Atexit simply registers them so that they are called after the main ends, as you can see from the name.

Atexit is a great tool for destroying global variables (classes) in the order you want them to be. For example, if there is a log class, you might call the log class to write a log in other global classes. So the log class has to be destructed last. If the destruction order is not specified, it is possible for the program to destroy the log class first when it exits, and other global classes will not be able to log correctly at this point.
Write the data back to the file, delete the temporary file, this is really useful.


Related articles: