为什么StandardOutput.Read()永远不会返回?(死锁?)

3
使用C#,我想自动化一个第三方Windows命令行程序。通常情况下,它是一个交互式控制台,您发送命令,它可能会提示详细信息,发送回结果并显示提示以请求更多命令。通常情况如下:
c:\>console_access.exe
Prompt> version
2.03g.2321
Prompt> 

我使用了.NET类Process和ProcessStartInfo,并利用标准输入/输出/错误流的重定向功能。
    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 -> result with no err(stdout上有内容,stderr上没有) * cmd -> error(stderr上有内容,stdout上没有) 没有问题。然而,对于一个特定的命令——在执行过程中提示输入密码——不起作用: * 主线程主循环永远循环 if (errorQueue.Count == 0 && outputQueue.Count == 0) { System.Threading.Thread.Sleep(500); } * 等待stdout的线程永远等待 byte b = (byte)myStandardOutput.Read(); * 等待一行stderr的线程永远等待 string message = myStandardError.ReadLine(); 我不明白为什么byte b = (byte)myStandardOutput.Read();没有输出消息“password:”。什么也没发生。我从未得到过第一个“p”。我觉得我遇到了死锁情况,但是我不理解为什么。有什么问题吗?(我认为这并不是非常相关,但我在Windows 7 32位上使用MS Visual Studio 2010的.NET 4.0上尝试了上述方法。)
1个回答

4
这是这些交互式控制台程序的常见故障模式。当检测到输出被重定向时,C运行库会自动将stderr和stdout流切换到缓冲模式。这样可以提高吞吐量。因此,输出进入缓冲区而不是直接写入控制台。让程序看到输出需要冲洗缓冲区。
有三种情况下缓冲区会被冲洗。当缓冲区满时(通常大约2千字节)会发生冲洗。或者当程序写入一个行终止符\n时也会发生冲洗。或者当程序显式调用fflush()时也会发生冲洗。前两种情况都不会发生,因为输出不足并且程序未使用\n。这指出了问题所在,原始程序员忘记调用fflush()。忘记这一点是非常普遍的,程序员只是没有打算以交互方式以外的方式使用该程序。
对此无可奈何,您需要请求程序所有者或作者添加fflush()。也许您可以假设提示信息正在被写入来应付当前情况。

我反复阅读了你的帖子,但仍然不理解。我尝试假设程序正在提示输入密码,所以我在轮询主线程队列之前将该密码发送到stdin => 但是没有用,行为相同。 希望原始程序被更改似乎不太合理(要求某人添加fflush())。 你是说我卡住了,除非采取其他选项,否则无法完成这个程序?Autoit?Expect? - Alex
1
要求程序员对其程序进行小改动是非常合理的。遇到难以进行微不足道的更改通常是业务问题,通常是由于会计试图节省开支所引发的。我们都憎恶他们。但当然,这是我们无法帮助您解决的问题。如果这是一个密码输入提示,则不能指望它能正常工作。当然,那是不应该正常工作的。 - Hans Passant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接