I have one program (a server) which prints four lines of output to the console, and then begins listening for an incoming connection from a client program.
I have another program (a tester) where I want to read the standard output from the server and analyze it. I have setup the tester program to start the server and get its output as follows:
Process server = new Process();
server.StartInfo.FileName = "server.exe";
server.StartInfo.UseShellExecute = false;
server.StartInfo.RedirectStandardInput = true;
server.StartInfo.RedirectStandardOutput = true;
server.StartInfo.RedirectStandardError = true;
server.Start();
StreamReader serverOutput = server.StandardOutput;
string line = serverOutput.ReadToEnd();
...
The problem I am experiencing is that when I execute the server myself (or when I execute it with the tester without redirected output) I can see all four lines on the console. However, when I use the above code to redirect the server output into the tester program, the tester program hangs on the "ReadToEnd" command as if it is waiting for more output from the server.
I have also tried using the "ReadLine" command and putting this into a FOR loop which repeats 4 times. When I do this the first three lines of output are picked up successfully, and then it hangs on the 4th "ReadLine" and never retrieves the 4th line of server output.
Finally, I have also tried using the "Read" command to try getting the characters one at a time, and still I cannot get any characters from the 4th line of server output.
Any suggestions as to what I am missing here?
Update:
After a massive amount of searching, I have finally determined that the problem is related to an issue with output buffering. The server program (written in C++) writes to cout
, which seems to be automatically flushed when printing to the screen, but not automatically flushed when redirecting stdout into the tester program. I can add setvbuf(stdout, NULL, _IONBF, 0);
to the server program to make stdout not be buffered, but I would prefer to find another solution which does not involve changing the server program.