I have a function that I want to run whenever my program exits:
void foo() {
std::cout<< "Exiting" << std::endl;
}
How do I register it to be run whenever the program exists, regardless of when and why it exits – due to signal, exit() call, etc?
You can use the aptly named
std::atexitfunction in thecstdlibheader:The system will maintain a stack of functions registered with
atexitand call them each in the reverse order of their registration when either theexitfunction is called, or the program returns frommain. You can register at least 32 functions this way.