Reputation: 107
I've got a C++ program which uses wprintf_s
function to print the results into the command line. But when I uses Process
in C# to read the output of the program, I cannot get any words of it. However when I added a fflush(stdout)
after the wprintf_s
statement, I can finally read the standard output in my C# program.
The code I use to start the progress is:
var proc = new Process {
StartInfo = new ProcessStartInfo {
FileName = "FILENAME",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
StringCollection values = new StringCollection();
proc.OutputDataReceived += (s, args) => {
lock (values) {
values.Add(args.Data);
}
};
proc.BeginOutputReadLine();
proc.WaitForExit();
Can anybody tell me why a fflush(stdout)
would work?
Upvotes: 3
Views: 721
Reputation: 87084
The output is being buffered in the C++ process and will remain so until the buffer is full or it is flushed, e.g. by calling fflush()
, by closing the stream, or other OS dependant reasons.
fflush()
just causes any data in the output buffer to be written to the stream.
If you don't want to explicitly call fflush()
, you can consider setting unbuffered mode on the output stream by calling setbuf()
with a NULL pointer for the second argument:
#include <stdio.h>
#include <unistd.h>
int main()
{
setbuf(stdout, (char *)NULL);
while (1)
{
fputs("hi there\n", stdout);
sleep(1);
}
}
Now the output will appear immediately.
Note that if stdout
is a terminal, setbuf(f, NULL)
is unnecessary as this is the default behaviour for terminal devices. If stdout
is a pipe, then setbuf(f, NULL)
will make it unbuffered.
Upvotes: 3