In C #, we use the following code to destroy a process tree. Sometimes it works, and sometimes it doesn’t, it may be related to Windows 7 and / or 64-bit.
The way he finds the children of this process is to call GetProcessesto get all the processes in the system, and then to call NtQueryInformationProcessto find out each process whose parent is this process. He does it recursively to walk on a tree.
The operational document states that NtQueryInformationProcessit should not be used. Instead, there is something called EnumProcesses, but I cannot find any examples in C #, only in other languages.
What a reliable way to kill a process tree in C #?
public static void TerminateProcessTree(Process process)
{
IntPtr processHandle = process.Handle;
uint processId = (uint)process.Id;
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
{
PROCESS_BASIC_INFORMATION procInfo = new PROCESS_BASIC_INFORMATION();
try
{
uint bytesWritten;
Win32Api.NtQueryInformationProcess(proc.Handle, 0, ref procInfo,
(uint)Marshal.SizeOf(procInfo), out bytesWritten);
if (procInfo.InheritedFromUniqueProcessId == processId)
{
TerminateProcessTree(proc);
}
}
catch (Exception )
{
}
}
if (!process.HasExited)
{
try
{
process.Kill();
}
catch { }
}
}