I am using an std::unique_ptr to manage some memory. This works correctly when my process exits normally since I can see the relevant constructor and destructor being invoked. However, when the process is killed with SIGTERM, I do not see the destructor being called. Is this expected behavior for std::unique_ptr when a process is terminated via a signal? Is there any way to get around this? Thanks in advance!
Asked
Active
Viewed 537 times
2
-
Possible duplicate https://stackoverflow.com/questions/4250013/is-destructor-called-if-sigint-or-sigstp-issued – Baum mit Augen Feb 17 '17 at 21:27
-
Also related https://stackoverflow.com/questions/9033931/memory-leak-c/9034141 – Baum mit Augen Feb 17 '17 at 21:29
-
1While user268396's answer is correct, you should be aware of the fact that writing a signal handler correctly is very difficult. It is illegal to access most global variables from within a signal handler, for example. If you want to know how to do it properly, I suggest posting a new question. – Brian Bi Feb 17 '17 at 21:59
1 Answers
3
That is to be expected: the default signal handlers will effectively call exit()
in your process, which will terminate the process. To get around this you should install a signal handler and take appropriate action when receiving a signal.

user268396
- 11,576
- 2
- 31
- 26
-
I am using a signal_handler to catch the signal and calling exit(0) within the same. Shouldn't that cause the unique_ptr to call the destructor for its stored pointer? – wishywashy Feb 17 '17 at 21:35
-
1@wishywashy: See [std::exit](http://en.cppreference.com/w/cpp/utility/program/exit), in particular: *"Stack is not unwound: destructors of variables with automatic [storage duration](http://en.cppreference.com/w/cpp/language/storage_duration) are not called."* – IInspectable Feb 17 '17 at 21:39
-
1The behaviour of a program after being terminated by a fatal signal is closer to calling `_exit` than `exit`. It does **not** run `atexit` handlers. – Brian Bi Feb 17 '17 at 21:55