0

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.

I tried running ProcessMonitor so check a sort of signal I can catch, but I did not find one.

I tried with a:

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

but it does nothing.

How can I do?

marco
  • 1,686
  • 1
  • 25
  • 33

1 Answers1

2

While the process is still alive, find the PID, and open it with OpenProcess. You’ll need at least SYNCHRONIZE permission.

Then wait for the handle to become signaled. For example, you can launch a new thread, and call WaitForSingleObject with INFINITE timeout. 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.

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.

Soonts
  • 20,079
  • 9
  • 57
  • 130
  • Ok, I will mark this as the right answer because I've also found out that there's no way without another process. – marco Aug 26 '20 at 14:13
  • @marco Imagine if a process *could* detect its own death. Then, you could make it so that when it gets killed, it keeps going. People who make viruses would love that! – user253751 Aug 26 '20 at 14:20
  • @marco You wrote you already have a service? If the user account running the service has permissions, the service can do what I wrote in the answer: detect termination of the process, and when detected, shutdown itself gracefully. Moreover, you probably already have some communication channel between your program and the service. You can use the same channel to tell the service about your program exiting normally, to disable the handling of killed/crashed process. – Soonts Aug 26 '20 at 14:33