<分区>
在 C# 中,我们使用以下代码来终止进程树。 有时有效,有时无效,可能与 Windows 7 和/或 64 位有关。
它找到给定进程的子进程的方法是通过调用 GetProcesses
获取系统中的所有进程,然后调用 NtQueryInformationProcess
找出父进程的每个进程是给定的过程。
它以递归方式执行此操作以遍历树。
在线文档说不应使用 NtQueryInformationProcess
。
相反,有一个名为 EnumProcesses
的东西,但我找不到任何 C# 示例,只能找到其他语言。
在 C# 中终止进程树的可靠方法是什么?
public static void TerminateProcessTree(Process process)
{
IntPtr processHandle = process.Handle;
uint processId = (uint)process.Id;
// Retrieve all processes on the system
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
{
// Get some basic information about the process
PROCESS_BASIC_INFORMATION procInfo = new PROCESS_BASIC_INFORMATION();
try
{
uint bytesWritten;
Win32Api.NtQueryInformationProcess(proc.Handle, 0, ref procInfo,
(uint)Marshal.SizeOf(procInfo), out bytesWritten); // == 0 is OK
// Is it a child process of the process we're trying to terminate?
if (procInfo.InheritedFromUniqueProcessId == processId)
{
// Terminate the child process (and its child processes)
// by calling this method recursively
TerminateProcessTree(proc);
}
}
catch (Exception /* ex */)
{
// Ignore, most likely 'Access Denied'
}
}
// Finally, terminate the process itself:
if (!process.HasExited)
{
try
{
process.Kill();
}
catch { }
}
}