问题
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.
回答1:
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.
回答2:
For normal closing applciation I would suggest
atexit()
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/6974822/shutdown-hook-c