简体   繁体   English

C++ - Windows - 从任务管理器中捕获进程退出

[英]C++ - Windows - catch process exit from Task Manager

I need to stop a service when our program has been killed with the task manager.当我们的程序被任务管理器杀死时,我需要停止服务。

I tried with std::signal(...) and _onexit(...) but it does not work.我尝试使用std::signal(...)_onexit(...)但它不起作用。

I tried running ProcessMonitor so check a sort of signal I can catch, but I did not find one.我尝试运行 ProcessMonitor,因此检查了一种我可以捕捉到的信号,但我没有找到。

I tried with a:我试过:

    auto serviceStopThread = QThread::create([](){
        ::WaitForSingleObject(::GetCurrentProcess(), INFINITE);
        ServiceUtils::stopService();
    });
    serviceStopThread->start();

but it does nothing.但它什么也不做。

How can I do?我能怎么做?

While the process is still alive, find the PID, and open it with OpenProcess .当进程还活着时,找到 PID,并使用OpenProcess打开它。 You'll need at least SYNCHRONIZE permission.您至少需要SYNCHRONIZE权限。

Then wait for the handle to become signaled.然后等待句柄发出信号。 For example, you can launch a new thread, and call WaitForSingleObject with INFINITE timeout.例如,您可以启动一个新线程,并使用INFINITE超时调用WaitForSingleObject The handle becomes signaled as soon as the process quits, regardless on the reason.无论出于何种原因,进程退出后,句柄就会立即发出信号。

React however you like but don't forget to call CloseHandle when you're done.随心所欲地做出反应,但不要忘记在完成后调用CloseHandle

If you only want to react when the process is killed suddenly, send some message to your supervising process when the program exits gracefully, to disable the handling.如果您只想在进程突然被杀死时做出反应,请在程序正常退出时向您的监督进程发送一些消息,以禁用处理。

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

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