C#結(jié)束進程及子進程
這是個我在C#調(diào)用批處理文件時遇到的問題。首先我通過Process.Start方法調(diào)用一個批處理文件,那個批處理文件里面則調(diào)用了一大堆程序。當(dāng)退出C#程序時,我在程序中結(jié)束殺掉了那個批處理文件的Process,但是,那個批處理所調(diào)用的子進程卻無法像直接調(diào)用批處理文件那樣隨著批處理文件的進程一起被殺掉,而是自動向上提升成為了獨立的進程。
在網(wǎng)上查了一下,可以通過NtQueryInformationProcess函數(shù)查詢子進程的信息,并同時也查到了一段殺掉進程及所有子進程的C#代碼,有需要的朋友可以參考一下。
static class ProcessExtend
{
// [StructLayout(LayoutKind.Sequential)]
private struct ProcessBasicInformation
{
public int ExitStatus;
public int PebBaseAddress;
public int AffinityMask;
public int BasePriority;
public uint UniqueProcessId;
public uint InheritedFromUniqueProcessId;
}
[DllImport("ntdll.dll")]
static extern int NtQueryInformationProcess(
IntPtr hProcess,
int processInformationClass /* 0 */,
ref ProcessBasicInformation processBasicInformation,
uint processInformationLength,
out uint returnLength
);
public static void KillProcessTree(this Process parent)
{
var processes = Process.GetProcesses();
foreach (var p in processes)
{
var pbi = new ProcessBasicInformation();
try
{
uint bytesWritten;
if (NtQueryInformationProcess(p.Handle, 0, ref pbi, (uint)Marshal.SizeOf(pbi), out bytesWritten) == 0) // == 0 is OK
if (pbi.InheritedFromUniqueProcessId == parent.Id)
using (var newParent = Process.GetProcessById((int)pbi.UniqueProcessId))
newParent.KillProcessTree();
}
catch { }
}
parent.Kill();
}
}PS:今天發(fā)現(xiàn)NtQueryInformationProcess函數(shù)在x64位程序上運行無效, 具體原因不明,Google了一下也沒有找到答案,反而找到了另一種解決方案,通過WMI來實現(xiàn)的。在x86和x64下都可以使用。
static void KillProcessAndChildren(int pid)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(pid);
Console.WriteLine(pid);
proc.Kill();
}
catch (ArgumentException)
{
/* process already exited */
}
}到此這篇關(guān)于C#結(jié)束進程及子進程的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實現(xiàn)的簡單隨機數(shù)產(chǎn)生器功能示例
這篇文章主要介紹了C#實現(xiàn)的簡單隨機數(shù)產(chǎn)生器功能,涉及C#簡單界面布局、事件響應(yīng)及隨機數(shù)生成相關(guān)操作技巧,需要的朋友可以參考下2017-09-09
C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容
這篇文章介紹了C#操作DataGridView獲取或設(shè)置當(dāng)前單元格的內(nèi)容,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-02-02
C#實現(xiàn)Word轉(zhuǎn)換TXT的方法詳解
這篇文章主要為大家詳細(xì)介紹了如何利用C#實現(xiàn)Word轉(zhuǎn)換TXT的功能,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下2022-12-12

