Click to See Complete Forum and Search --> : Reading stdout within MFC


Cloud3x3
June 18th, 2010, 09:28 PM
Hello everybody, this is my first post here. I'm been scouring the internets trying to find a solution to my problem. I have an MFC application, and I would like to be able to read stdout into a buffer so that I can do things with the output. The reason being, I am linking to libs that use stdout to print debug information, and I have no way of controlling where those libs write. So, I've tried the whole CreatePipe, SetSTDHandle, thing, but I get a stall when I go to ReadFile on the stream. My code looks something like:

HANDLE read;
HANDLE write;
CreatePipe(&read, &write, 0, 8192);
bool b = SetStdHandle( STD_OUTPUT_HANDLE, write );
b = SetStdHandle( STD_ERROR_HANDLE, write );
printf("ceci n'est pas une pipe");
printf("and more!");
fflush(stdout);
FlushFileBuffers(read);
FlushFileBuffers(write);
DWORD bytes_read;
b = ReadFile(read, buffer, 1000, &bytes_read, NULL );

Everything seem to be returning true except when it comes to the ReadFile. The app will just hang there forever and never return. Anyone know how to get around this or what's going on?

MrViggy
June 21st, 2010, 11:47 AM
Yes, ReadFile (http://msdn.microsoft.com/en-us/library/aa365467%28VS.85%29.aspx) is a blocking function. It doesn't return unless there is an error, or the specified number of bytes have been read (or, if you use it asynchronously; I believe that has to do with overlapped I/O).

Viggy

Igor Vartanov
June 22nd, 2010, 02:52 AM
As for me, it would be more natural to dump the stdout to a file rather than a buffer.