C#關閉進程樹

來源:互聯網
上載者:User
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 可以通過以下代碼來實現關閉一個進程樹:ref: http://www.codeproject.com/KB/shell/ManageProcessShellAPI.aspx?fid=275098&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2638740#xx2638740xxusing System;<br />using System.Diagnostics;<br />using System.Globalization;<br />using System.Management;</p><p>namespace xxx<br />{<br /> public static class ProcessesKiller<br /> {<br /> public static void FindAndKillProcess(int id)<br /> {<br /> killProcess(id);<br /> }</p><p> public static void FindAndKillProcess(string name)<br /> {<br /> foreach (Process clsProcess in Process.GetProcesses())<br /> {<br /> if ((clsProcess.ProcessName.StartsWith(name, StringComparison.CurrentCulture)) || (clsProcess.MainWindowTitle.StartsWith(name, StringComparison.CurrentCulture)))<br /> killProcess(clsProcess.Id);<br /> }<br /> }</p><p> private static bool killProcess(int pid)<br /> {<br /> Process[] procs = Process.GetProcesses();<br /> for (int i = 0; i < procs.Length; i++)<br /> {<br /> if (getParentProcess(procs[i].Id) == pid)<br /> killProcess(procs[i].Id);<br /> }</p><p> try<br /> {<br /> Process myProc = Process.GetProcessById(pid);<br /> myProc.Kill();<br /> }<br /> // process already quited<br /> catch (ArgumentException)<br /> {<br /> ;<br /> }</p><p> return true;<br /> }</p><p> private static int getParentProcess(int Id)<br /> {<br /> int parentPid = 0;<br /> using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString(CultureInfo.InvariantCulture) + "'"))<br /> {<br /> try<br /> {<br /> mo.Get();<br /> }<br /> catch (ManagementException)<br /> {<br /> return -1;<br /> }<br /> parentPid = Convert.ToInt32(mo["ParentProcessId"], CultureInfo.InvariantCulture);<br /> }<br /> return parentPid;<br /> }<br /> }<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.