I'm having a hard time deciphering the MSDN doc about Process.StandardOutpout as to if the Read(Char[], Int32, Int32) method blocks or not. My understanding is that it shouldn't block, but it seems like it does when I set RedirectStandardInput to true.
Does anybody have experience with this; or some explanation for the issue I'm having?
The context here is that I don't want to wait for a full line (ie with a line terminator), or for the process to exit before reading standard output. Also I don't want to use callbacks. I want to read StdOut synchronously as the process writes to it.
Here is a simplified version of my code:
string command = @"C:flex_sdksflex_sdk_4.5.1.21328infcsh.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = false; # <-- if I set this to true, then
# the program hangs on
# p.StandardOutput.Read later on
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.Start();
StringBuilder sb_stdout = new StringBuilder(1024);
char[] buffer = new char[64];
int nb_bytes_read;
while (true) {
do {
nb_bytes_read = p.StandardOutput.Read(buffer, 0, buffer.Length);
sb_stdout.Append(new string(buffer, 0, nb_bytes_read));
} while (nb_bytes_read > 0);
if (sb_stdout.ToString().EndsWith("
(fcsh) "))
break;
Thread.Sleep(20);
}
Update
Based on my (probably bad) assumption that Process.StandardOutput is broken when used:
- with stdin redirected; and,
- while reading something else than terminated lines from stdout or stderr,
I decided to try using Windows' API directly. I added an answer with such code; it works fine (at least for now).
Another update
I created a blog entry with the code I now use.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…