使用 dup 后恢复标准输出 [英] Restoring stdout after using dup
问题描述
使用 fork
我创建了一个孩子,在孩子中我使用 execl
执行 ls
命令.为了将输出发送给父级,我使用了 pipe
和 dup
.然后父级打印输出.该代码给出了预期的输出,但是当我尝试恢复最初保存在 stdout_holder
中的 stdout
时,终端上没有打印任何内容(当我使用 printf("hello") 或它下面的 execl 语句).然而,经过几次观察,观察到 hello
仅在第一次重定向1"后什么都不做时才会打印.(如果我在 dup(fd[1],1)
之后不做任何事情而只做 dup(stdout_holder,1)
)为什么会这样?
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);
}
}
推荐答案
如 这个文件 你应该在改变它之前保存标准输出文件描述符:
As in line 63 of this file you should save stdout file descriptor before changing it:
int moutfd = dup(STDOUT_FILENO);
dup2(fd, STDOUT_FILENO);
// Do the going-to-be-buffered jobs
dup2(moutfd, STDOUT_FILENO);
close(moutfd);
close(fd);
这篇关于使用 dup 后恢复标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!