c# - 在 WaitForExit C# 控制台应用程序上终止命令的问题
问题描述
我正在通过创建新进程使用 C# 控制台应用程序执行 Cmd 命令。面临在 WaitforExit 上终止进程的问题。
基本上我想在waitforexit 上终止命令执行。 请帮忙。
代码:
string Command = "perl Simple_File_Copy.pl"
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.FileName = "cmd.exe";
procStartInfo.Arguments = "/c " + Command + " & exit";
procStartInfo.WorkingDirectory = ProcessDirectory;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
procStartInfo.WindowStyle = ProcessWindowStyle.Normal;
Process process = Process.Start(procStartInfo);
if (!process.WaitForExit((int)TimeSpan.FromSeconds(10).TotalMilliseconds)) //wait for 10 seconds
{
Console.WriteLine("TimeOut Exception");
// the perl command still contiue its exeuction if I use any of
below.
//Want to terminate the command line step at this stage
process.Kill();
process.CloseMainWindow();
process.Close();
}
解决方案
由于您的应用程序正在创建其他进程,因此您需要终止整个进程树(在您的示例中 cmd 被终止,但 cmd 正在运行另一个运行 perl 脚本的应用程序并且没有被终止)。杀死整棵树的示例代码:
用法
KillProcessAndChildren(process.Id);
方法
/// <summary>
/// Kill a process, and all of its children, grandchildren, etc.
/// </summary>
/// <param name="pid">Process ID.</param>
private static void KillProcessAndChildren(int pid)
{
// Cannot close 'system idle process'.
if (pid == 0)
{
return;
}
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.
}
}
参考: 在 C# 中以编程方式终止进程树
推荐阅读
- dart - 如何在 Flutter 中使用 Bloc 正确设置 DropdownButton 的值?
- swift - SpriteKit Particle Emitter - 粒子在创建后是否会受到力的影响
- python - 满足条件时列表中的值总和
- java - 我无法在 Android 8 Oreo(华为)中选择 PDF 文件
- hyperledger-fabric - Hyperledger Fabric - Orderer 日志在广播期间显示错误,即使交易成功并提交给所有对等方
- c++ - Vulkan 中的 YCbCr 采样器
- javascript - angular 6中带有http调用的custome管道不返回值
- vba - 如何从当前选择开始在文档中查找单词
- java - 无法延迟初始化集合和故障安全清理
- sql - 是否可以在 SQL 中查询服务器的 dns 别名