CRT function atexit()
could register a function to run after main
function returns. I am wondering what's the typical scenario to use this? Is it (atexit
) really necessary?
The atexit() function registers the given function to be called at normal process termination, either via exit(3) or via return from the program's main(). Functions so registered are called in the reverse order of their registration; no arguments are passed.
The function pointed by atexit() is automatically called without arguments when the program terminates normally. In case more than one function has been specified by different calls to the atexit() function, all are executed in the order of a stack (i.e. the last function specified is the first to be executed at exit).
The C library function int atexit(void (*func)(void)) causes the specified function func to be called when the program terminates. You can register your termination function anywhere you like, but it will be called at the time of the program termination.
You may call atexit() up to 32 times in a program. If you register more than one function in this way, they will be called in LIFO order: the last function registered will be the first one called when your program exists.
I guess its primary use is when you don't have control over main
and you want to make sure something is called at the end of it.
It's sometimes used by libraries that don't want to insist that the user program calls their cleanup functions explicitly before terminating the program.
It's also used in the phoenix singleton pattern (see Modern C++ Design by Andrei Alexandrescu).
It can be used for what you want that need to be executed EVERYTIME an application is shutting down. By using that, you don't need to bloat your code by adding all the cleanup code before each exit() you can find in your code.
Some use cases :
One of the main uses of atexit
is for libraries to perform cleanup on program exit. Note that atexit
is called when exit
is called, not when the program aborts or crashes, so you can't do cleanup on assertion failures and so on. It is also not called if the program calls exec
.
You can call it directly in the main program if you want, if you have a library that might call exit for some reason.
Note that you can only register a limited number of atexit
handlers, where 'limited' depends on your operating system, and so it returns an error status.
It gives C programs a similar ability to calling the destructor of a static variable in C++.
I've used it to delete temporary files, or (once or twice) to reset some hardware registers. Generally it's not necessary to use it to close files or rlease memory, because the O/S will do that for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With