I have a function that I want to run whenever my program exits:
void foo() {
std::cout<< \"Exiting\" << std::endl;
}
How do I reg
I am answering as a Linux user, but all of this should apply to windows.
I had this similar question, so hopefully I can sum up previous answers and add my two cents.
Signals and abort()
: ^C
and ^Z
can be "intercepted" to call your function before exiting, presumably with exit(). Signals SIGQUIT
AKA ^\
and SIGKILL
which has no key stroke cannot be intercepted. Here's an example for using the csignal
header and a C++ lambda.
#include
#include
#include
using namespace std;
int main()
{
//signal requires lam take an int parameter
//this parameter is equal to the signals value
auto lam =
[] (int i) { cout << "aborting" << endl; exit(0); };
//^C
signal(SIGINT, lam);
//abort()
signal(SIGABRT, lam);
//sent by "kill" command
signal(SIGTERM, lam);
//^Z
signal(SIGTSTP, lam);
while(1)
{
}
return 0;
}
Exit: Since I used exit()
in my examples above, care must be taken here. If the function being run is a clean-up function that only needs to run once, perhaps a static variable has_run
could be used. Or in the example above, raise()
a signal that you can't intercept. But those tend to come with core dumps which just feels dirty. Your choice, here. An example follows
#include
#include
using namespace std;
int main()
{
//called with no parameters
auto lam = [] () { cout << "at exit"; };
atexit(lam);
return 0;
}
Take note that c++11 added a quick_exit
which has an accompanying at_quick_exit
which act the same as above. But with quick_exit
no clean up tasks are performed. In contrast, with exit
object destructors are called and C streams are closed, with only automatic storage variables not getting cleaned up.