tags:

views:

260

answers:

3

I'm creating new processes using System.Diagnostics.Process class from my application. I want this processes to be killed when/if my application is crashed. But if I kill my application from Task Manager, child processes are not killed. Is there any way to make child processes dependent on parent process?

+1  A: 

One way is to pass PID of parent process to the child. The child will periodically poll if the process with the specified pid exists or not. If not it will just quit.

You can also use Process.WaitForExit method in child method to be notified when the parent process ends but it might not work in case of Task Manager.

Giorgi
How can I pass parent PID to child? Is there any system solution? I can't modify child process binaries.
Idsa
Well, if you can't modify child process you can not use my solution even if you pass PID to it.
Giorgi
A: 

You can do it with an additional control process

eg.

String lParentPath = "c:\\Core Temp.exe";
String lChildPath = "c:\\zzz.txt";
List<Process> lChildren = new List<Process>();

Process lParent = Process.Start(lParentPath);

for (int i = 0; i < 10; i++)
  lChildren.Add(Process.Start(lChildPath));

lParent.WaitForExit();

foreach (Process lChild in lChildren)
  lChild.Kill();
Turek
A: 

I see two options:

  1. If you know exactly what child process could be started and you are sure they are only started from your main process, then you could consider simply searching for them by name and kill them.
  2. Iterate through all processes and kill every process that has your process as a parent (I guess you need to kill the child processes first). Here is explained how you can get the parent process id.
Stefan Egli