【问题标题】:Program doesn’t terminate when using processes使用进程时程序不会终止
【发布时间】:2011-09-19 10:50:24
【问题描述】:

使用ProcessStartInfoProcess 我想启动一个程序(例如getdiff.exe),然后读取程序产生的所有输出。稍后我将以更具建设性的方式使用数据,现在我只想打印数据以确保其正常工作。但是,程序并没有按应有的方式终止。有人知道为什么吗?提前谢谢你。

ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;                
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";

Process p = Process.Start(psi);
string read = p.StandardOutput.ReadToEnd();
p.WaitForExit();

Console.WriteLine(p);
Console.WriteLine("Complete");

p.Close();

把程序改成这样就可以正常工作了:

ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;                
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";

Process p = Process.Start(psi);
StreamReader read = p.StandardOutput;

while (read.Peek() >= 0)
    Console.WriteLine(read.ReadLine());

Console.WriteLine("Complete");
p.WaitForExit();
p.Close();

【问题讨论】:

  • 它的哪一部分没有按应有的方式终止?您的应用程序,还是被调用的进程?
  • 为什么要终止?它是控制台应用程序吗?还有什么?
  • 这是一个更大程序中的函数。但是当单独运行时,程序永远不会终止。所以它不健康。

标签: c# process processstartinfo


【解决方案1】:
ProcessStartInfo psi = new ProcessStartInfo("getdiff.exe");
psi.Arguments = "DIFF";
psi.UseShellExecute = false;                
psi.RedirectStandardInput = true;
psi.WorkingDirectory = "c:\\test";

Process p = Process.Start(psi);
StreamReader read = p.StandardOutput;

while (read.Peek() >= 0)
    Console.WriteLine(read.ReadLine());

Console.WriteLine("Complete");
p.WaitForExit();
p.Close();

【讨论】:

    【解决方案2】:

    The MSDN provides a good example 如何重定向进程输入/输出。 ReadToEnd() 无法正确确定流的结尾。 MSDN says

    ReadToEnd 假设流知道它何时结束。对于交互式协议,服务器仅在您请求时才发送数据而不关闭连接,ReadToEnd 可能会无限期阻塞,应避免使用。

    编辑: 避免ReadToEnd() 的另一个原因:非常快的进程会导致异常,因为必须在程序输出任何数据之前重定向流。

    【讨论】:

      【解决方案3】:

      试试这个代码,

      p.CloseMainWindow()

      【讨论】:

        【解决方案4】:

        不确定它是否相关,但你在 psi.RedirectStandardInput = true; 没有对结果流做任何事情。也许,不知何故,应用程序要求输入流在退出之前“关闭”?所以试试myProcess.StandardInput.Close()

        【讨论】:

        • 我也看到了。并且psi.RedirectStandardOutput = true; 终止程序。输出很奇怪,但它终止了。
        猜你喜欢
        • 2014-07-10
        • 1970-01-01
        • 1970-01-01
        • 2016-04-16
        • 1970-01-01
        • 1970-01-01
        • 2017-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多