【发布时间】:2021-10-09 20:12:15
【问题描述】:
对于我的管道函数,我正在使用 fork() 创建两个子进程,并在调用 execvp() 之前尝试将第一个子进程的内容通过管道传递给第二个子进程。我做错了什么,好像我做 ls -la |此外,输出是目录中文件的垂直列表。我对c(和c)中的管道非常陌生,所以很可能这是一个被忽视的错误。任何帮助表示赞赏!
void handle_pipe_cmds(char **args1, char **args2){
char ** word1 = parse_space(*args1);
char ** word2 = parse_space(*args2);
int p[2];
pipe(p);
pid_t pid = fork();
if (pid == -1) {
printf("CANNOT FORK!");
} else if (pid == 0) {
dup2(p[1], STDOUT_FILENO);
close(p[1]);
int status = execvp(word1[0], word1);
if (status != 0) {
printf("%s failed\n", word1[0]);
exit(1);
}
exit(0);
} else {
close(p[1]);
wait(NULL);
}
pid = fork();
if (pid == -1) {
printf("CANNOT FORK!");
} else if (pid == 0) {
dup2(p[0], STDIN_FILENO);
close(p[1]);
close(p[0]);
int status = execvp(word2[0], word2);
if (status != 0) {
printf("%s failed\n", word2[0]);
exit(1);
}
exit(0);
} else {
close(p[1]);
close(p[0]);
wait(NULL);
}
}
【问题讨论】:
-
你为什么认为这是错误的?如果您在常规 shell 中运行该命令,它不会做同样的事情吗?