我想通过递归函数处理c中的多个管道。我无法弄清楚是什么问题。我是不是没有正确地连接管道,还是我把一些工艺挂起来了。请给出一些建议。 假设:令牌[0] =" ls&#34 ;; token [1] =" |&#34 ;; token [2] =" sort&#34 ;; token [3] =" |&#34 ;; token [4] =" more&#34 ;;
int pipeExecution(char *token[]) {
int isPipe = 0;
int fds[2] = {0};
pid_t pid;
for (int i = 0; token[i] != NULL; i++) {
if (strcmp(token[i], "|") == 0) {
isPipe = 1;
token[i] = NULL;
if (pipe(fds) < 0) {
perror("Can not pipe\n");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("Can not fork() **1\n");
exit(EXIT_FAILURE);
} else {
if (pid > 0) {
pid = fork();
if (pid < 0) {
perror("Can not fork() **2\n");
exit(EXIT_FAILURE);
} else {
if (pid > 0) { // parent
wait(NULL);
} else { // child 2 - excuse the command after a "|"
close(fds[1]); // does not write to pipe
if (dup2(fds[0], STDIN_FILENO) < 0) {
perror("Can not dup2()\n");
exit(EXIT_FAILURE);
}
printf("execute tokens after |\n");
pipeExecution(token + (i + 1));
}
}
} else { // child 1 - excuse the command before a "|"
printf("execute tokens before |\n");
close(fds[0]); // does not read from pipe
if (dup2(fds[1], STDOUT_FILENO) < 0) {
perror("Can not dup2()\n");
exit(EXIT_FAILURE);
}
execvp(token[0], token);
}
}
break;
}
}
if (isPipe == 0) {
perror(token[0]);
pid = fork();
if (pid < 0) {
perror("Can not fork()\n");
exit(EXIT_FAILURE);
}
if (pid > 0) {
wait(NULL);
} else {
execvp(token[0], token);
}
}
return 0;
}