首页 > 解决方案 > 在 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();
        }

标签: c#.netconsole-application

解决方案


由于您的应用程序正在创建其他进程,因此您需要终止整个进程树(在您的示例中 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# 中以编程方式终止进程树


推荐阅读