c# - 为什么 StandardOutput.Read() 永远不会返回? (僵局?)

标签 c# deadlock

我想使用 C# 自动化第三方 Windows 命令行程序。通常,它是一个交互式控制台,您发送命令,它可能会提示详细信息,发回结果并显示提示以询问更多命令。通常:

c:\>console_access.exe
Prompt> version
2.03g.2321
Prompt> 

我使用了 .NET 类 Process 和 ProcessStartInfo 以及 stdin/stdout/stderr 的重定向。

    public ConsoleAccess()
    {
        if (!File.Exists(consoleAccessPath)) throw new FileNotFoundException(consoleAccessPath + " not found");

        myProcess = new Process();
        ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(consoleAccessPath, ""); // even "2>&1" as argument does not work; my code still hangs
        myProcessStartInfo.CreateNoWindow = true; 
        myProcessStartInfo.UseShellExecute = false; 
        myProcessStartInfo.RedirectStandardOutput = true;
        myProcessStartInfo.RedirectStandardError = true;
        myProcessStartInfo.RedirectStandardInput = true;
        //myProcessStartInfo.ErrorDialog = true; // I tried, to no avail.
        myProcess.StartInfo = myProcessStartInfo;

        outputQueue = new ConcurrentQueue<string>(); // thread-safe queue
        errorQueue = new ConcurrentQueue<string>();

        myProcess.Start();
        myStandardOutput = myProcess.StandardOutput;
        myStandardError = myProcess.StandardError;
        myStandardInput = myProcess.StandardInput;

        stdOutPumper = new Thread(new ThreadStart(PumpStdOutLoop));
        stdOutPumper.Start();
        stdErrPumper = new Thread(new ThreadStart(PumpStdErrLoop));
        stdErrPumper.Start();

        string empty = getResponse(); // check for prompt
        string version = getVersion(); // one simple command
    }
    // [...]
    private void PumpStdErrLoop()
    {
        while (true)
        {
            string message = myStandardError.ReadLine();
            errorQueue.Enqueue(message);
        }
    }

    private void PumpStdOutLoop()
    {
        while (true)
        {
            bool done = false;
            string buffer = "";
            //int blocksize = 1024;
            string prompt = "Prompt> ";
            while (!done)
            {
                //char[] intermediaire = new char[blocksize];
                //int res = myStandardOutput.Read(intermediaire, 0, blocksize);
                //buffer += new string(intermediaire).Substring(0, res);
                byte b = (byte)myStandardOutput.Read(); // I go byte per byte, just in case the char[] above is the source of the problem. To no avail.
                buffer += (char)b;
                done = buffer.EndsWith(prompt);
            }
            buffer = buffer.Substring(0, buffer.Length - prompt.Length);
            outputQueue.Enqueue(buffer);
        }
    }

由于该程序在等待命令时返回“Prompt>”(重要:末尾没有“\n”),所以我不能使用 myProcess.BeginOutputReadLine();

但是,我必须使用线程,因为我必须同时监听 stdout 和 stderr。

这就是我为类生产者/消费者模式使用线程和线程安全队列的原因。

“您可以使用异步读取操作来避免这些依赖关系及其潜在的死锁。或者,您可以通过创建两个线程并在单独的线程上读取每个流的输出来避免死锁情况。”来源:http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput%28v=vs.100%29.aspx

有了这个设计,所有的序列都像 * cmd -> 结果没有错误(stdout 上有内容,stderr 上没有内容) * cmd -> 错误(stderr 上有错误,stdout 上没有错误) 按预期工作。没问题。

  • cmd -> 结果带有警告(stderr 和 stdout 都有) 应该有效(我正在尝试重现这种情况)

但是,特别是对于一个命令——在执行过程中提示输入密码的命令——不起作用:

  • 主线程主体永远循环 if (errorQueue.Count == 0 && outputQueue.Count == 0) { System.Threading.Thread.Sleep(500); }
  • 线程泵标准输出永远等待 byte b = (byte)myStandardOutput.Read();
  • thread pumping stdout 永远等待一条线 string message = myStandardError.ReadLine();

我不明白的是为什么 byte b = (byte)myStandardOutput.Read(); 不发送消息“password:”。什么都没发生。我从来没有得到第一个“p”。

我觉得我陷入了僵局,但我不明白为什么。

怎么了?

(我认为这不是很相关,但我在 Windows 7 32 位上使用 MS Visual Studio 2010 在 .NET 4.0 上尝试了上述内容。)

最佳答案

对于此类交互式控制台模式程序,这是一种非常常见的故障模式。当 C 运行时库检测到输出被重定向时,它会自动将 stderr 和 stdout 流切换到缓冲模式。对提高吞吐量很重要。因此输出进入该缓冲区而不是直接写入控制台。让您的程序看到输出需要刷新缓冲区。

缓冲区在三种情况下会被刷新。当缓冲区已满(通常约为 2 KB)时会发生刷新。或者当程序写入行终止符 (\n) 时。或者当程序显式调用 fflush() 时。前两种情况不会发生,没有足够的输出并且程序没有使用\n。问题出在哪里,原来的程序员忘了调用fflush()。忘记这一点是非常常见的,程序员根本没有打算以交互方式以外的方式使用该程序。

对此无能为力,您需要请求程序的所有者或作者添加 fflush()。假设正在编写提示,也许您可​​以一瘸一拐地走下去。

关于c# - 为什么 StandardOutput.Read() 永远不会返回? (僵局?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15086115/

相关文章:

c# - 如何通过 ProtoBuf-net 使用 DateTimeKind 选项序列化 DateTime 字段

c# - 在 .NET 中求解方程

C++ 确定是否附加了调试器

c# - 如何安全地解决 BeforeFieldInit 和静态构造函数循环?

c# - int 和 string 之间的唯一索引

c# - 在 C# 中,为什么在这种情况下使用字段与自动实现的属性会导致不同的行为?

mysql - MySQL 上的死锁与锁等待超时

c# - Parallel.ForEach 与 ReaderWriterLockSlim 中的死锁

c++ - 线程内的死锁

c# - TDD - 为什么这个 Assert.AreSame 通过?