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?
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 :
- Clean a temporary folder
- Print a memory dump
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.
When writing libraries ... Imagine a library that on crashes save the stack on a pre-defined path (or mails the trace).
EDIT - as mentioned on the comment, this answer is wrong. Don't read it. Too late.
Exceptions can be handled in atexit ().Assume multi process environment. There is one hardware resource is physically available. Any one of the process can use that h/w at a time. Now process1 is acquired the h/w resource and after processing process1 not released h/w resource. To release the h/w resource this atexit() may be used, so that process2 can acquire h/w effectively.
© 2022 - 2024 — McMap. All rights reserved.
main
or on a just-in-time basis) is one use. – Burkleyatexit()
is a standard C function and is mandated by each of the C standards (C90, C99, C11, C18, C23, …). It is not specific to the Microsoft runtime environment. – Geography