I am trying to use a pipe to rederect stdout into a pipe and read it later. I will use this later with fork(), where the child process starts a different program that I need to comunicate with. This is my Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
int main(){
printf("Starting Test\n");
int myPipe[2], nbytes;
char readbuffer[80];
pipe(myPipe);
int backup = dup(1); //store stdout
if (dup2(1,myPipe[1])< 1){printf("error");} //copy stdout in the input end of my pipe
printf("in pipe\n"); //print something in stdout -> in my pipe
nbytes = read(myPipe[0],readbuffer,sizeof(readbuffer)); //read output of my pipe
dup2(myPipe[1],backup); // restore stdout
printf("recived: %s",readbuffer); //prit out what I recived
return 0;
}
I expected it to print out:
Starting Test
recived: in pipe
But the output that I get is:
Starting Test
in pipe
recived: @����U
So I assume that stdout was not copied properly, as I get the "in pipe" before the "recived: ..." But the dup2() call throws no errors.
I read some tutorials, mostly this one https://tldp.org/LDP/lpg/node11.html but I can't find my error... Thank you for your help!
The code has a couple of problems:
In dup2(1,myPipe[1])
the parameters are back to front. That makes mypipe[1]
be the same as 1
. But instead you need it to be the other way around: dup2(myPipe[1],1)
dup2(myPipe[1],backup)
is also wrong. That makes backup
be the same as mypipe[1]
. What you want instead is to make 1
the same as backup: dup2(backup, 1)
.
Smaller problem but printf
does not output a NUL character. So the read
will not result in a valid NUL terminated string. Solve that by initialising: char readbuffer[80] = "";