关闭挂钩 c++
无论何种终止(异常、正常、未捕获的异常等),是否有某种方法可以在终止时运行代码? 我知道它在 Java 中实际上是可能的,但是在 C++ 中也可能吗?我假设一个Windows环境。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不 - 如果有人调用
TerminateProcess
,您的进程将被销毁,无需进一步告别,并且(特别是)在关闭过程中没有机会运行更多代码。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
解决该问题的一个好方法是使用 C++ RAII 习惯用法,这意味着可以将清理操作放在对象的析构函数中,即
请参阅 ACE 库中的对象生命周期管理器。在链接的文档中,他们还讨论了 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.
See the Object Lifetime Manager in ACE library. At the linked document, they discuss about the
atexit
function as well.不以任何形式终止;有些信号被设计为不被处理,例如 Linux 上的 KILL。
这些信号旨在终止消耗了所有内存、CPU 或其他一些资源的程序,并使计算机处于难以运行处理程序函数的状态。
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.