Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to intercept a process "Kill" command in Windows (.NET)?

Tags:

.net

windows

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.

like image 766
Sako73 Avatar asked Dec 28 '25 17:12

Sako73


2 Answers

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.

like image 149
SecurityMatt Avatar answered Dec 30 '25 14:12

SecurityMatt


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

like image 34
Erik Philips Avatar answered Dec 30 '25 15:12

Erik Philips