views:

40

answers:

2

Imagine, we have two .net applications. Application "A" starts application "B" using System.Diagnostics.Process class. Then "A" wants to kill "B" by method Process.Kill. How "B" can determine that somebody is killing him?

A: 

I don't think it's possible for the application to respond to being killed... I think it operates more at the OS level like when using task manager.

Using Process.Kill() might not be right in this context, can you provide more information about the problem you are trying to solve?

Ian
Yeah, I found that "A process cannot prevent itself from being terminated." I think we don't have an opportunity to determine it.http://msdn.microsoft.com/en-us/library/ms686714(VS.85).aspx
alga
A: 

Maybe you could try it this way within Process B's code...

// We're in Process B....
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
proc.EnableRaisingEvents = true;
proc.Exited += new EventHandler(proc_Exited);

static void proc_Exited(object sender, EventArgs e)
{
   // Handle here that we got killed...
}

I cannot say with confidence that this will work...the very nature of the OS that sends a 'Kill' to a process is implementation dependant, and as such, there is no guaranteed foolproof way of Process B in knowing that it is being killed. As you have not stated explicitly if process B is a managed/unmanaged process, I will make the basis of the assumption that it is indeed managed as the tag is '.net', If it's a WinForm application, perhaps a Closing event within winForms will have a reason in that event handler's argument or use an ApplicationDomain instance as shown below:

AppDomain thisDom = AppDomain.CurrentDomain;
thisDom.ProcessExit += new EventHandler(thisDom_ProcessExit);
//

static void thisDom_ProcessExit(object sender, EventArgs e)
{
   // Handle the situation here where the AppDomain is going to be unloaded and killed!
}

Hope this helps, Best regards, Tom.

tommieb75