Shutdown Hook c++

断了今生、忘了曾经 提交于 2019-12-23 09:16:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!