What function in C++ is guaranteed to be called during abrupt termination or exit which can perform the clean up activity ..
Depending on what you mean by "abrupt termination" there are several different options:
main
, or call to exit()
).atexit()
registers a function to be called on normal termination.std::set_terminate
registers a function that will be called when an exception is thrown but not caught, or when "exception handling has to be terminated for some other reason".sigaction()
registers functions to be called when your program receives signals, many of which will normally abruptly terminate your program. Signal handlers may be called when the program is in an internally-inconsistent state, and therefore are extremely limited in what they can do. For instance, they cannot do anything that might allocate memory. Also, this API is not available on Windows; there are equivalents but I am not familiar with them.Note that all operating systems in common use provide at least one way to abruptly terminate your program that cannot be intercepted from your code. For instance, Unix has signal 9 (SIGKILL
) which you can't register a handler for. This is a feature, not a bug. You, the user, need a way to make a process go away even if it has done everything in its power to make itself indestructible. Furthermore, no code can protect your process when the user's pet rabbit gnaws through the power cord on the computer. Because of this, it might be a better use of your time to design your program to recover from crashes cleanly, rather than trying to clean up when a crash happens. See this article on "crash-only design" for more about that.
Read about atexit
here. However it will not be called in all cases (for example, calling abort
will not trigger the function you registered with atexit
).
You can implement your own signal handler, then all the signals will pass there and you can do whatever for each of them.
You are looking for set_terminate()
.
http://www.cplusplus.com/reference/std/exception/set_terminate/
There are other similar function in the same header, that are usable for complementary scenarios.
int main()
{
try
{
// all your code here
}
catch(...)
{
// cleanup
}
return 0;
}
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