7

I have a windows C++ application (app.exe). When the app is closed, I need to perform some cleanup tasks specific to my application. What happens when this process (app.exe) is killed through the Task Manager. Assuming that the application is still responsive, can I somehow handle this situation in my app.exe?

I am looking for something similar to how kill <pid> in Linux will send the SIGTERM signal to the process indicated by pid. I could then register my own signal handler for SIGTERM and perform the cleanup.

Umair
  • 862
  • 4
  • 10
  • 16

3 Answers3

12

There are two ways to kill application in Task Manager.

  • Killing through Applications tab would roughly be equivalent of SIGTERM. Application may intercept it and do more processing, since it's basically sending a "close window" message. Message to catch is WM_CLOSE.
  • Killing through Processes tab would roughly be equivalent of SIGKILL. There is nothing you can do to intercept that, short of monitoring user's actions in Task Manager's listbox and End Process button, or having a watchdog process that will see when the first one is killed.

Alternatively, design the application in a way that does not require cleanup, or in a way that it will perform cleanup at startup.

Ivan Vučica
  • 9,529
  • 9
  • 60
  • 111
  • Unfortunately, can't re-design the app. Its a 10 year old legacy app with several thousand lines of code. – Umair Oct 06 '09 at 19:36
  • 1
    Note, googlers: there's no `WM_CLOSE` in a console app, though. There you'd need to call `SetConsoleCtrlHandler` for registering your handler to process `CTRL_CLOSE_EVENT` for closing (i.e. "SIGTERM"). – Sz. Aug 15 '19 at 15:47
1

I think you will need another PID that is monitoring the PID of your app.exe and does the necessary work at the time.

Raj More
  • 47,048
  • 33
  • 131
  • 198
0

That depends, if the user chooses to "End Task" your application you will be notified and you can handle it see this.

but if the user chooses to end the process, you have no way to handle it in your application. the easiest way would be a second process or you can inject into process manager and hook the TerminateProcess API.

Mehran
  • 1,977
  • 1
  • 18
  • 33