简体   繁体   English

如何保证在c ++中进程退出或被杀死时执行某些代码?

[英]How to guarantee some code to be executed when the process exits or gets killed in c++?

Could anyone tell me how to ensure some code in my program gets executed when its process exits or gets killed? 谁能告诉我如何确保程序中的某些代码在进程退出或被杀死时得以执行?

The destroyer only gets called when it exits normally. 驱逐舰只有在正常退出时才会被呼叫。 But I want my code get executed when it's killed by a system shutdown or task manager. 但是我希望我的代码在被系统关闭或任务管理器杀死后被执行。

The platform is Windows and I don't mind using platform specific code if it's needed. 该平台是Windows,如果需要,我不介意使用平台特定的代码。

You can't. 你不能 What if the user pulls out the power cord? 如果用户拔出电源线怎么办?

Ending a task from Task Manager or from a Windows shutdown will both give the process a chance to shutdown gracefully by sending messages such as WM_CLOSE , which you can use to close down your process gracefully. 任务管理器或Windows 关闭结束任务都将通过发送诸如WM_CLOSE消息使该进程有一个正常关闭的机会,您可以使用这些消息来正常关闭进程。 However, as per @immibis answer, there are scenarios where this cannot be guaranteed. 但是,按照@immibis的答案,在某些情况下无法保证。

假设程序正在以或多或少的控制方式崩溃,也许atexit是最好的选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM