Solved

How to kill a spawned process?

Posted on 2008-06-15
3
1,675 Views
Last Modified: 2010-04-21
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!
0
Comment
Question by:oxyoo
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 10

Author Comment

by:oxyoo
ID: 21790774
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

0
 
LVL 1

Accepted Solution

by:
gregmulvihill earned 500 total points
ID: 21791840
I adapted a solution (http://blogs.msdn.com/bclteam/archive/2006/06/20/640259.aspx) presented by Robert Villahermosa to deal with multiple process instances of the same name.  Pass in the process ID of the server you started with System.Diagnostics.Process, and FindChildProcessIDs should return an array with all the spawned process IDs.  Then you can iterate through the list and kill the processes.

Example:

int[] oChildProcessIDs = FindChildProcessIDs(nServiceProcessID);

foreach (int nProcessID in oChildProcessIDs)
{
      Process oProcess = Process.GetProcessById(nProcessID);
      oProcess.Kill();
      oProcess.Dispose();
}




		public static int[] FindChildProcessIDs(int nParentProcessID)
		{
			List<int> oChildProcessIDs = new List<int>();
 
			foreach (Process oProcess in Process.GetProcesses())
			{
				Process oParentProcess = FindParentProcess(oProcess);
 
				if ((null != oParentProcess) && (nParentProcessID == oParentProcess.Id))
				{
					oChildProcessIDs.Add(oProcess.Id);
				}
			}
 
			return oChildProcessIDs.ToArray();
		}
 
		
		public static Process FindParentProcess(Process oTargetChildProcess)
		{
			Process oParentProcess = null;
 
			Process[] oChildProcessList = Process.GetProcessesByName(oTargetChildProcess.ProcessName);
 
			for (int nIndex = 0; nIndex < oChildProcessList.Length; nIndex++)
			{
				string sChildProcessName = oTargetChildProcess.ProcessName;
 
				if (nIndex != 0) sChildProcessName += "#" + nIndex;
 
				PerformanceCounter oChildProcessID = new PerformanceCounter("Process", "ID Process", sChildProcessName);
				PerformanceCounter oParentProcessID = new PerformanceCounter("Process", "Creating Process ID", sChildProcessName);
 
				int nChildProcessID = (int)oChildProcessID.NextValue();
				int nParentProcessID = (int)oParentProcessID.NextValue();
 
				oChildProcessID.Dispose();
				oParentProcessID.Dispose();
 
				if (oTargetChildProcess.Id == nChildProcessID)
				{
					try
					{
						oParentProcess = Process.GetProcessById(nParentProcessID);
 
						break;
					}
					catch { }
				}
			}
 
			return oParentProcess;
		}

Open in new window

0
 
LVL 10

Author Closing Comment

by:oxyoo
ID: 31467371
Thanks, an excellent solution!
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Suggested Courses

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question