这篇文章主要讲解了“C#如何结束进程及子进程”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“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:今天发现NtQueryInformationProcess函数在x64位程序上运行无效, 具体原因不明,Google了一下也没有找到答案,反而找到了另一种解决方案,通过WMI来实现的。在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 */
}
}
感谢各位的阅读,以上就是“C#如何结束进程及子进程”的内容了,经过本文的学习后,相信大家对C#如何结束进程及子进程这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。