gpt4 book ai didi

c# - Process.Kill() 似乎没有终止进程

转载 作者:可可西里 更新时间:2023-11-01 03:08:09 24 4
gpt4 key购买 nike

我在使用 Process.Kill() 时遇到问题。我想我一定是误解了它是如何工作的。这是我的测试功能。我启动了一个长时间运行的进程 (ping -t),然后在五秒后将其终止。

我可以看到 ping 进程出现,但在我的程序完成后该进程仍然存在。我必须手动杀死它。

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);

ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
Process process = new Process();

startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.Arguments = "/c ping -t 8.8.8.8";

Console.WriteLine("Staring ping process");
process.StartInfo = startInfo;
process.Start();
Thread.Sleep(5000);

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);
Thread.Sleep(5000);

Console.WriteLine("Killing ping process");
process.Kill();
Thread.Sleep(5000);

Console.WriteLine("Total number of ping processes is {0}", Process.GetProcessesByName("ping").Length);

我在这里做错了什么?

最佳答案

您启动了 cmd.exe,然后 cmd.exe 启动了子进程 ping.exe。要杀死 ping.exe,您可以杀死所有进程层次结构。例如使用 WMI(添加 System.Management 引用):

private static void KillProcessAndChildrens(int pid)
{
ManagementObjectSearcher processSearcher = new ManagementObjectSearcher
("Select * From Win32_Process Where ParentProcessID=" + pid);
ManagementObjectCollection processCollection = processSearcher.Get();

try
{
Process proc = Process.GetProcessById(pid);
if (!proc.HasExited) proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}

if (processCollection != null)
{
foreach (ManagementObject mo in processCollection)
{
KillProcessAndChildrens(Convert.ToInt32(mo["ProcessID"])); //kill child processes(also kills childrens of childrens etc.)
}
}
}

关于c# - Process.Kill() 似乎没有终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com