3

I have a Windows console application written in .NET 4.0 (c#), and if the application/process is killed abnormally (e.g. from Task Manager, or by a operating system shutdown), is there any way to intercept this so that some cleanup code could be executed?

Thanks for any help.

Sako73
  • 9,957
  • 13
  • 57
  • 75
  • Insert commentary on "how safe would it be to try to execute cleanup if the entire process is being taken down." – Anthony Pegram Mar 06 '12 at 18:21
  • Check this: http://stackoverflow.com/questions/838261/handling-end-process-of-a-windows-app The version of .net is different but the concept still holds. – seth Mar 06 '12 at 18:21

3 Answers3

4

You cannot detect that your own process is being killed. When someone calls NtTerminateProcess() with your process, and they have permission to do so, you don't get told. Your threads all stop and your process vanishes from underneath you.

Thankfully most cleanup doesn't need to be done manually - all of that memory you hadn't free'd will be reclaimed by the OS, all of those system handles you didn't close will get cleaned up automatically and all of the temporary files that you had opened as TEMPORARY (you do do that right?) will be automatically deleted.

The reason for this is simple. If you've decided to kill a program via Task Manager - that's because the user has decided it is misbehaving. If you then tell it to stop misbehaving, well it might ignore you because, well it's misbehaving.

It seems that a better way for you to do your process management would be to provide a legitimate way for you to exit the process - be it via a window that handles the WM_CLOSE event or by running it in a console which can be aborted via the red-X button in the corner. Task manager is meant to be a measure of last resort. If the user is going to the trouble to Ctrl+Alt+Del your process to death, you don't get a second chance.

SecurityMatt
  • 6,593
  • 1
  • 22
  • 28
2

Take a look at Win32.SystemEvents there are good examples of how to detect these events..

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
0

There generally isn't any way to handle a process that is being killed, but you should be able to handle the events that occur on application exit. (Just think: if you could handle a process being killed, it would be really really easy to write some terrible spyware type stuff). If I remember correctly, there is a way of checking why the app is closing. Depending on what is causing it to close, you can react differently.

Joel B
  • 801
  • 1
  • 11
  • 30