http://www.cnblogs.com/TianFang/archive/2010/05/19/1739614.html
正好碰到這位一樣的問題,就直接轉過來了
這是個我在C#調用批次檔時遇到的問題。首先我通過Process.Start方法調用一個批次檔,那個批次檔裡面則調用了一大堆程式。當退出C#程式時,我在程式中結束殺掉了那個批次檔的Process,但是,那個批處理所調用的子進程卻無法像直接調用批次檔那樣隨著批次檔的進程一起被殺掉,而是自動向上提升成為了獨立的進程。
在網上查了一下,可以通過NtQueryInformationProcess函數查詢子進程的資訊,並同時也查到了一段殺掉進程及所有子進程的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();
}
}