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.
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.
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.
精彩评论