如何解决Dup2() 使用和输出重定向
我正在尝试将一个进程的输出重定向到另一个进程的 0
。这是由 stdin
完成的。我的问题是:在函数终止后,dup2()
和 stdin
是否返回到它们的 stdout
,或者我是否必须执行类似 place(0,1)
的操作。更清楚的是,在一个命令的函数终止后,在第二次调用时 savestdin = dup(0)
和 stdin
处于它们假定的位置吗?
解决方法
要让您的 stdout
转到fork
ed 进程'stdin
,您需要结合使用 pipe
和 dup
。还没有测试过,但它应该会给你一些希望:
int my_pipe[2];
pipe(my_pipe); // my_pipe[0] is write end
// my_pipe[1] is read end
// Now we need to replace stdout with the fd from the write end
// And stdin of the target process with the fd from the read end
// First make a copy of stdout
int stdout_copy = dup(1);
// Now replace stdout
dup2(my_pipe[0],1);
// Make the child proccess
pid_t pid = fork();
if (pid == 0)
{
// Replace stdin
dup2(my_pipe[1],0);
execv(....); // run the child program
exit(1); // error
}
int ret;
waitpid(pid,&ret,0);
// Restore stdout
dup2(stdout_copy,1);
close(stdout_copy);
close(my_pipe[0]);
close(my_pipe[1]);
所以回答你的问题,当你使用dup2()
替换0
和1
时,除非你用{{1}保存原始文件描述符,否则它们不会恢复到终端}} 并使用 dup()
手动恢复它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。