3

C# を使用して、サードパーティの Windows コマンドライン プログラムを自動化したいと考えています。通常、これは対話型のコンソールであり、コマンドを送信すると、詳細を求めるプロンプトが表示され、結果が返され、さらにコマンドを要求するプロンプトが表示されます。通常:

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

stdin/stdout/stderr のリダイレクトとともに、.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 を同時にリッスンする必要があるため、スレッドを使用する必要があります。

これが、クラス プロデューサー/コンシューマー パターンにスレッドとスレッド セーフ キューを使用した理由です。

「非同期読み取り操作を使用して、これらの依存関係とデッドロックの可能性を回避できます。別の方法として、2 つのスレッドを作成し、別のスレッドで各ストリームの出力を読み取ることで、デッドロック状態を回避できます。」ソース: 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 の両方で何か) が機能するはずです (このシナリオを再現しようとしています)

ただし、特に 1 つのコマンド (実行中にパスワードの入力を求めるコマンド) は機能しません。

  • メイン スレッドのプリンシパルが永久にループする if (errorQueue.Count == 0 && outputQueue.Count == 0) { System.Threading.Thread.Sleep(500); }
  • スレッド ポンピング stdout は永久に待機します byte b = (byte)myStandardOutput.Read();
  • スレッド ポンピング stdout は、ラインを永久に待機します string message = myStandardError.ReadLine();

私が得られないのは、なぜbyte b = (byte)myStandardOutput.Read();「password:」というメッセージを送信しないのかということです。何も起こりません。最初の 'p' が得られません。

デッドロック シナリオに陥ったように感じますが、その理由がわかりません。

どうしたの?

(あまり関連性があるとは思いませんが、Windows 7 32 ビット上の MS Visual Studio 2010 を使用して .NET 4.0 で上記を試しました。)

4

1 に答える 1

3

これは、この種の対話型コンソール モード プログラムでよくある障害モードです。C ランタイム ライブラリは、出力がリダイレクトされていることを検出すると、stderr ストリームと stdout ストリームを自動的にバッファー モードに切り替えます。スループットを向上させるために重要です。したがって、出力はコンソールに直接書き込まれるのではなく、そのバッファーに入れられます。プログラムに出力を表示させるには、バッファをフラッシュする必要があります。

バッファがフラッシュされる 3 つのシナリオがあります。フラッシュは、バッファがいっぱいになると発生します (通常は約 2 キロバイト)。または、プログラムが行末記号 (\n) を書き込むとき。または、プログラムが明示的に fflush() を呼び出す場合。最初の 2 つのシナリオは発生せず、十分な出力がなく、プログラムが \n を使用していません。この問題は、元のプログラマーが fflush() を呼び出すのを忘れていたことを示しています。これを忘れることは非常によくあることです。プログラマーは、プログラムをインタラクティブな方法以外で使用することをまったく意図していませんでした。

それについては何もできません。プログラムの所有者または作成者に fflush() を追加するよう依頼する必要があります。プロンプトが書かれていると仮定するだけで、足を引きずることができるかもしれません。

于 2013-02-26T13:35:01.003 に答える