在此函数中,如何进行此操作以便父级停止尝试从管道中读取。即如果我运行命令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]);
}
答案 0 :(得分: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);
}