Reputation: 1011
As the title says Im trying to redirect stdout, to test I have the following program:
#include <windows.h>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#define BUFFER_SIZE 4096
int main(int argc, char* argv[])
{
int fdStdOutPipe[2];
int fdStdOut;
printf("Console Print...\n");
// Start
fflush(stdout);
_pipe(fdStdOutPipe, BUFFER_SIZE, O_RAW);
fdStdOut = _dup(_fileno(stdout));
_dup2(fdStdOutPipe[1], _fileno(stdout));
setvbuf( stdout, NULL, _IONBF, 0 );
fdStdOut = _dup(_fileno(stdout));
printf("Buffer Print...\n");
char buffer[ BUFFER_SIZE ] = "";
while( _read( fdStdOutPipe[0], buffer, BUFFER_SIZE ) )
{
// Test
int l = strlen( buffer );
buffer[ 0 ] = 0;
}
// Close
_dup2(fdStdOut, _fileno(stdout));
_close(fdStdOut);
_close(fdStdOutPipe[0]);
_close(fdStdOutPipe[1]);
printf("Console Print Again...\n");
return 0;
}
The issue that Im having is that after that _read is blocking if the stdout pipe is empty... I was under the impression that pipes are non block by default. Is there any way that I can make the pipe in the example above non block?
Upvotes: 2
Views: 489
Reputation: 26
Before calling _read(), check the pipe status can solve the problem. I'm using this code on VC++ and works fine.
struct _stat st;
if(_fstat(fdStdOutPipe[0], &st)) {
// do error handling
}
if (st.st_size) {
// data is available to read
while(_read(...)) {
}
}
Upvotes: 1