Dup2() 使用和输出重定向

问题描述

我正在尝试将一个进程的输出重定向到另一个进程的 0。这是由 stdin 完成的。我的问题是:在函数终止后,dup2()stdin 是否返回到它们的 stdout,或者我是否必须执行类似 place(0,1) 的操作。更清楚的是,在一个命令的函数终止后,在第二次调用savestdin = dup(0)stdin 处于它们假定的位置吗?

解决方法

要让您的 stdout 转到forked 进程'stdin,您需要结合使用 pipedup。还没有测试过,但它应该会给你一些希望:

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()替换01时,除非你用{{1}保存原始文件描述符,否则它们不会恢复到终端}} 并使用 dup() 手动恢复它。