Link to home
Start Free TrialLog in
Avatar of oxyoo
oxyooFlag for Sweden

asked on

How to kill a spawned process?

Hi,

I'm running an external server using System.Diagnostics.Process, the problem
is that this server spawns another process.
So far I am only able to close/kill the first process but not the spawned one.
Is there some way to track all spawned processes and kill them on demand?

I can not kill it by name alone, since this is a common thread name, which could
mean that I kill some other apps process.

Thanks!
Avatar of oxyoo
oxyoo
Flag of Sweden image

ASKER

I think I have what is needed now, after a lot of research. The code
is pretty ugly but so far does the job.

Can anyone find any flaws with it?

What the code does is that iterates through all the processes and
finds the parentId, then compares it with my runningServer process
to see if it is the parent. If yes, it kills it.

                int parentId = runningServer.Id;
 
                foreach (Process process in Process.GetProcesses()) {
                    PerformanceCounter myParentMultiProcID = new PerformanceCounter("Process", "ID Process",
                                                                                    process.ProcessName);
 
                    try {
                        float tmpParentPID = myParentMultiProcID.NextValue();
 
                        if (tmpParentPID == parentId) {
                            process.Kill();
                            process.Dispose();
                        }
                    }
                    catch (InvalidOperationException) {}
                }
 
 
                // NOT NEEDED?
                try {
                    runningServer.Kill();
                    runningServer.Dispose();
                    runningServer = null;
                }
                catch (InvalidOperationException) {}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Member_2_991834
Member_2_991834

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oxyoo

ASKER

Thanks, an excellent solution!