Using fork
I created a child and in the child I'm executing the ls
command using execl
. To send the output to parent,I used pipe
and dup
. The parent then prints the output. The code gives the expected output, but when I tried to restore back the stdout
which I saved initially in stdout_holder
, nothing is printed on terminal (when I used printf("hello") or the execl statement below it).
However after few observations, it is observed that hello
is printed only when nothing is done after redirecting "1" for the first time. (If I don't do anything after dup(fd[1],1)
and simply do dup(stdout_holder,1)
)
Why is this happening?
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<errno.h>
#include<sys/wait.h>
#include<stdlib.h>
#include<string.h>
int main()
{int fd[2],stdout_holder;
char str;
pid_t pid;
pipe(fd);
pid=fork();
if(pid==0)
{ stdout_holder=dup(1);
close(fd[0]);
printf("stdout_holder=%d\n",stdout_holder);
fd[1]=dup2(fd[1],1);
execl("/bin/ls","ls","-l",NULL);
stdout_holder=dup2(stdout_holder,1);
printf("hello\n"); //Terminal doesnt show output.
execl("/bin/ls","ls","-l",NULL); //Terminal doesnt show output
}
else
{ close(fd[1]);
wait(&pid);
while(read(fd[0],&str,1)>0)
printf("%c",str);
}
}