http://blog.csdn.net/ffeiffei/article/details/5897003
Windows并不维护进程间的父子关系链,而是提供了另外一个妥协的办法 - Job对象。你可以自己维护相关的多个进程,或把多个进程放入一个Job对象中,以便统一管理。Windows task manager中"End Process" & "End Process Tree"分别对应kill掉一个单独的进程和一个进程树。关闭一个进程树,与之所有相关的进程也被关闭了;通常,Windows task manager中关闭一个父进程,其子进程不会被关闭(Windows并不维护进程间的父子关系链)。
分析进程的工具Process explorer:
http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx
可以通过以下代码来实现关闭一个进程树:
- using System;
- using System.Diagnostics;
- using System.Globalization;
- using System.Management;
- namespace xxx
- {
- public static class ProcessesKiller
- {
- public static void FindAndKillProcess(int id)
- {
- killProcess(id);
- }
- public static void FindAndKillProcess(string name)
- {
- foreach (Process clsProcess in Process.GetProcesses())
- {
- if ((clsProcess.ProcessName.StartsWith(name, StringComparison.CurrentCulture)) || (clsProcess.MainWindowTitle.StartsWith(name, StringComparison.CurrentCulture)))
- killProcess(clsProcess.Id);
- }
- }
- private static bool killProcess(int pid)
- {
- Process[] procs = Process.GetProcesses();
- for (int i = 0; i < procs.Length; i++)
- {
- if (getParentProcess(procs[i].Id) == pid)
- killProcess(procs[i].Id);
- }
- try
- {
- Process myProc = Process.GetProcessById(pid);
- myProc.Kill();
- }
- // process already quited
- catch (ArgumentException)
- {
- ;
- }
- return true;
- }
- private static int getParentProcess(int Id)
- {
- int parentPid = 0;
- using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString(CultureInfo.InvariantCulture) + "'"))
- {
- try
- {
- mo.Get();
- }
- catch (ManagementException)
- {
- return -1;
- }
- parentPid = Convert.ToInt32(mo["ParentProcessId"], CultureInfo.InvariantCulture);
- }
- return parentPid;
- }
- }
- }