is there some way to run code on termination, no matter what kind termination (abnormal,normal,uncaught exception etc.)? I know its actually possible in Java, but is it even possible in C++? Im assuming a windows environment.
No -- if somebody invokes TerminateProcess
, your process will be destroyed without further adieu, and (in particular) without any chance to run any more code in the process of shutting down.
atexit()
and you can catch most signals using signal()
-- however you can never take any action if somebody forces termination ( that would be kill-9 on Linux, and signal 9 is uncatchable) –
Pillow For normal closing applciation I would suggest
atexit()
One good way to approach the problem is using the C++ RAII idiom, which here means that cleanup operations can be placed in the destructor of an object, i.e.
class ShutdownHook {
~ShutdownHook() {
// exit handler code
}
};
int main() {
ShutdownHook h;
//...
}
See the Object Lifetime Manager in ACE library. At the linked document, they discuss about the atexit
function as well.
exit()
call, or due to segmentation fault, etc. –
Kink Not for any kind of termination; there are signals that are designed to not be handled, like KILL on Linux.
These signals are designed to terminate a program that has consumed all memory, or CPU, or some other resources, and has left the computer in a state that makes it difficult to run a handler function.
© 2022 - 2024 — McMap. All rights reserved.