Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling end process of a windows app

Is it possible to capture the task manager end process of a windows application within the same windows application itself? I am using a C# 2.0 win app and I would like to do some database processing (change a flag from 'Y' to 'N' in the DB) when an end process happens.

like image 219
SO User Avatar asked May 08 '09 04:05

SO User


People also ask

What happens if you end a Windows process?

If you try to use the End Process command on the Task Manager, Windows will warn you that this is a bad idea. Do it anyway, and your PC will go completely black with no hope for recovery. You'd have to reboot to get it running again at that point.


2 Answers

No, it is not possible to hook the operating system's decision to end a process. Note, this is not done by task manger, ending a process is the responsibility of the kernel.

You will need to do two things here:

  1. Connect event handlers to the normal user interface messages that tell a application to exit. Use these events to persist data, free resources, and otherwise exit cleanly.
  2. Handle exceptions as appropriate to catch errors and clean up and save data if possible.

Here are a three links to Raymond's blog explaining why you cannot do what you are asking.

  • Why can't you trap TerminateProcess?
  • Why do some process stay in Task Manager after they've been killed?
  • The arms race between programs and users

Also, I addressed a similar StackOverflow question here.

like image 51
Foredecker Avatar answered Sep 30 '22 12:09

Foredecker


How about a slightly different approach:

Have your application update a date time field e.g. LastPollDate every so often while it is running, and have a separate field e.g. "AppTerminatedNormally" which you set to N, and change to Y if you get a form close event.

If the app is killed via Task Manager, the date will not be updated any more, and your AppTerminatedNormally will still be no.

This way you could run a query that finds all rows where LastPollDate is older than 10 minutes and AppTerminatedNormally is N, and you would have all the sessions that were abnormally terminated.

like image 35
Bork Blatt Avatar answered Sep 30 '22 13:09

Bork Blatt