【发布时间】:2020-08-14 14:13:06
【问题描述】:
我正在尝试制作一个 linux shell 模拟器,但是当输入是具有超过 2 个管道的命令时,我遇到了麻烦。这是我的代码:
int Executa_Fork(char ***comando,int npipe){
pid_t pid;
int status,i,j;
int **pipefd;
pipefd = malloc(sizeof(int *)*(npipe));
for(i = 0;i < npipe;i++){
pipefd[i] = malloc(sizeof(int)*2);
}
for(i = 0;i <= npipe;i++){
if(npipe != i){
if (pipe(pipefd[i]) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
if(pid == 0){ //processo filho
printf("filho");
if(i == 0){
dup2(pipefd[i][1], 1);
close(pipefd[i][0]);
close(pipefd[i][1]);
}else if(i != npipe){
dup2(pipefd[i-1][0], 0);
dup2(pipefd[i][1], 1);
close(pipefd[i][0]);
close(pipefd[i][1]);
close(pipefd[i-1][0]);
close(pipefd[i-1][1]);
}else{
dup2(pipefd[i-1][0], 0);
close(pipefd[i-1][0]);
close(pipefd[i-1][1]);
}
printf("%s %s\n", comando[i][0], comando[i][1]);
if(execv(comando[i][0],comando[i]) == -1){
perror("exec");
exit(EXIT_FAILURE);
}
}
}
return 1;
}
npipe 是输入命令的管道号,comando 存储命令,comando[command index] 是要执行的命令。如果有人可以帮助我找到一种方法来执行超过 2 个管道命令,我将非常感激。
【问题讨论】: