在 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 { }
}
}
Use ManagmentObjectSearcher
和一点递归:
private 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);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)