2

在这个函数中,我如何使父停止尝试从管道中读取。即,如果我运行命令 ls | grep test grep 不会输出test然后test.c等待用户输入?

pipe(pipefd);

int pid = fork();
if (pid != 0) {
    dup2(pipefd[0], STDIN_FILENO);
    int rv2 = execv(get_contain_dir(command_to), args_to);
    close(pipefd[0]);
} else {
    dup2(pipefd[1], STDOUT_FILENO);
    int rv1 = execv(get_contain_dir(command_from), args_from);
    close(pipefd[1]);
}
4

1 回答 1

2

您没有正确关闭管道。每个进程必须关闭它不使用的管道:

int pid = fork();
if (pid != 0) {
    dup2(pipefd[0], STDIN_FILENO);
    close(pipefd[1]); // not using the left side
    int rv2 = execv(get_contain_dir(command_to), args_to);

} else {
    dup2(pipefd[1], STDOUT_FILENO);
    close(pipefd[0]);  // not using the right side 
    int rv1 = execv(get_contain_dir(command_from), args_from);
}
于 2013-10-30T07:11:17.743 回答