Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function guaranteed to be called in C++ during abrupt termination or exit

What function in C++ is guaranteed to be called during abrupt termination or exit which can perform the clean up activity ..

like image 478
NoName Avatar asked Aug 01 '11 16:08

NoName


4 Answers

Depending on what you mean by "abrupt termination" there are several different options:

  • Global destructors will be called upon normal termination (return from 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.

like image 155
zwol Avatar answered Nov 20 '22 07:11

zwol


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.

like image 41
littleadv Avatar answered Nov 20 '22 07:11

littleadv


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.

like image 1
Šimon Tóth Avatar answered Nov 20 '22 09:11

Šimon Tóth


int main()
{
    try
    {
        // all your code here
    }
    catch(...)
    {
        // cleanup
    }
    return 0;
}
like image 1
Moo-Juice Avatar answered Nov 20 '22 08:11

Moo-Juice