-
redirect STDOUT to pipes
Hey,
I'm trying to redirect stdout, so it goes into a pipe, so I can do something like this:
printf("Hey there!\n");
then read from the pipe and get "Hey there!".
The code I'm trying to use for this is the following:
Code:
// Redirect output to file
int pipePair[2];
if(pipe(pipePair) != 0) {
fprintf(stderr,"Could not create pipe. Skipping command\n");
exit(1);
}
if (dup2(pipePair[1], STDOUT_FILENO) == -1) {
fprintf(stderr, "Error\n");
exit(1);
}
char buffer[100];
memset(buffer,0,100);
printf("Hey there!\n");
read(pipePair[0],buffer,3); // Read only the first 3 letters just in case
printf("%s\n", buffer);
Now, this code don't return.
read() blocks, because for some reason.
If I write manually to the pipe by saying write(pipePair[1]......blabla),
it don't block, but it never recieves anything from stdout, so it seems the redirection failed.
Anyone see what I do wrong?
-
Interestingly, I'm having the same issue. One that I found is that if you do a fflush(stdou) prior to the read, you'll get data.
Also, as an aside, I can get the data instantly IFF I'm on the other side of a fork(), which is really strange.
Something for everyone else: Is there a way to control the trigger level of a 2.6.++ pipe???
-
What your doing is bad practice (regardless of whether or not it works for you), because your relying on the stdout buffer to hold any data you may printf out until you get around to reading it.
You should always be waiting to collect the data before you even start writing it. I would use a separate thread myself, but doing it from a fork as Kennedy mentioned works too.