I use the following code to redirect stdout to a pipe, then read all the data from the pipe to the buffer. I have 2 problems:
first problem: when I send a line (after redirection) more than the BUFF_SIZE pipe, the program stops responding (dead end or something else).
second problem: when I try to read from a pipe before something was sent to stdout. I get the same answer, the program stops responding - the _read command is stuck ...
The problem is that I do not know the amount of data that will be sent to the channel after the redirect.
The first problem, I do not know how to handle, and I will be happy for the help. The second problem, which I solved in a simple workaround, immediately after the redirection, I print a space character in stdout. but I think this solution is not correct ...
#include <fcntl.h>
#include <io.h>
#include <iostream>
#define READ 0
#define WRITE 1
#define BUFF_SIZE 5
using namespace std;
int main()
{
int stdout_pipe[2];
int saved_stdout;
saved_stdout = _dup(_fileno(stdout));
if(_pipe(stdout_pipe,BUFF_SIZE, O_TEXT) != 0 )
{
exit(1);
}
fflush( stdout );
if(_dup2(stdout_pipe[1], _fileno(stdout)) != 0 )
{
exit(1);
}
ios::sync_with_stdio();
setvbuf( stdout, NULL, _IONBF, 0 );
printf("123456");
char buffer[BUFF_SIZE] = {0};
int nOutRead = 0;
nOutRead = _read(stdout_pipe[READ], buffer, BUFF_SIZE);
buffer[nOutRead] = '\0';
if (_dup2(saved_stdout, _fileno(stdout)) != 0 )
{
exit(1);
}
ios::sync_with_stdio();
printf("buffer: %s\n", buffer);
}
source
share