进程WaitForExit()永远不会结束(cmd openfiles)

时间:2014-10-01 12:17:04

标签: c# process cmd windows-server-2008-r2

此代码在我的测试系统(原始Windows Server 2008 R2的副本)上运行良好

private string _getNetFiles()
{
    // prepare execution process
    ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c openfiles /query /Fo list");
    processStartInfo.CreateNoWindow = true;
    processStartInfo.UseShellExecute = false;
    processStartInfo.RedirectStandardError = true;
    processStartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(437);
    processStartInfo.RedirectStandardOutput = true;

    // execute
    Process process = Process.Start(processStartInfo);
    process.WaitForExit();


    // read outputs
    string stdOutput = process.StandardOutput.ReadToEnd();
    string stdError = process.StandardError.ReadToEnd();

    return stdOutput;
}

在原始系统上: 我看到" cmd.exe / c openfiles / query / Fo list"任务管理器中的任务,但此任务永远不会结束(process.WaitForExit()进程永远不会结束)。 原系统上的Cmd: openfiles / query / fo list 也很好用!

问题出在哪里?

关于raiserle

编辑: 我可以使用任务管理器停止该过程。 stdOutput是正确的。为什么不结束cmd-taks。

1 个答案:

答案 0 :(得分:4)

子进程要么等待输入要么要读取其输出。管道缓冲区不是无限大。您需要不断消耗标准输出和标准误差。

Get Values from Process StandardOutput看起来很合理。 https://stackoverflow.com/a/24084220/122718记录了如何安全地读取两个流。

另请注意Visual Basic Capture output of cmd以及everything that Hans Passant says on this topic

在没有输出重定向的情况下使用Process类非常棘手并且记录不清。

相关问题