【问题标题】:Process.Kill not killing processProcess.Kill 不杀死进程
【发布时间】:2011-08-31 19:05:42
【问题描述】:

我编写了一些代码来与经常挂起的控制台应用程序进行交互(由于有错误的 COM 互操作,我无法控制)。我的方法包括在超时后调用Process.Kill(),但它似乎并没有杀死进程——它仍然出现在任务管理器中。这段代码有问题吗?

private static string CallBuggyConsoleApp(string path, string ext) {
    var startInfo = new ProcessStartInfo {
        FileName = ConsoleAppPath,
        Arguments = String.Format("\"{0}\" {1}", path, ext),
        UseShellExecute = false,
        RedirectStandardOutput = true,
        RedirectStandardError = true
    };
    using (var proc = Process.Start(startInfo)) {
        //The line above should be replaced with:
        //using (var proc = new Process()) {
        //    proc.StartInfo = startInfo;
        var output = new StringBuilder();
        var error = new StringBuilder();
        proc.OutputDataReceived += (_, args) => output.Append(args.Data);
        proc.ErrorDataReceived += (_, args) => error.Append(args.Data);
        proc.Start();
        proc.BeginOutputReadLine();
        proc.BeginErrorReadLine();
        if (proc.WaitForExit((int)ConsoleAppTimeout.TotalMilliseconds)) {
            proc.WaitForExit();
            if (proc.ExitCode != 0) {
                throw new Exception(String.Format("Pid {0} exited at {1} with exit code {2} and the following error: {3}",
                    proc.Id, proc.ExitTime, proc.ExitCode, error.ToString()));
            }
            return output.ToString();
        }
        proc.CancelOutputRead();
        proc.CancelErrorRead();
        proc.Kill();
        proc.WaitForExit();
        throw new Exception(String.Format("Killed pid {0} at {1}", proc.Id, proc.ExitTime));
    }
}

【问题讨论】:

  • 为什么proc.Start被执行了两次? proc.Kill 行是否真的执行(用调试器检查)?这是什么类型的 COM 组件(COM/COM+/DCOM..)?
  • 你在什么操作系统上运行,进程提升了吗?

标签: c# .net process


【解决方案1】:

在您执行第一次抛出的代码内部,您没有调用Kill

一般Exception 不应该在 throws 中使用,更常见的是抛出它的一些派生类,例如 ApplicationException 或其他更专业的类。

除此之外,你为什么要调用 start 两次?只调用一次 start 会有什么表现?你觉得有什么不同吗?

【讨论】:

  • 啊,大概就是这样!我没有注意到我给Start 打了两次电话。闲置的进程很可能不是被杀死的进程。
  • 没有问题。我也会尝试您的相同代码,但启动另一个应用程序,例如 notepad.exe,以确保它与另一个可执行文件按预期工作......
  • 可能是个好主意。谢谢。是的,删除另一个对Start 的调用似乎已经修复了它。我想我正在寻找一个接受ProcessStartInfo 的构造函数,最终调用Start,然后忘记了它。在连接事件处理程序后,我自动插入了对Start 的第二次调用。
  • 请注意,如果进程启动失败,Process.Start会返回null。
  • @High:很高兴知道。谢谢。我没有经常使用Process,所以我担心我的代码有问题。
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-14
  • 1970-01-01
  • 2010-12-08
  • 2016-01-24
相关资源
最近更新 更多