在 linux shell 模拟器中执行超过 2 个管道的麻烦 (c)

trouble to exec more than 2 pipes in a linux shell simulator (c)

我正在尝试制作一个 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[命令索引]是要执行的命令。如果有人能帮我找到一种方法来执行超过 2 个管道命令,我将不胜感激。

你的麻烦在于,如果你有这样的管道:

cmd1 | cmd2 | cmd3 | cmd4

(通过管道 P1、P2、P3 连接),然后在您处理 cmd3 时,父进程打开了 P1、P2 和 P3,子进程也打开了。并且您的子代码会小心地关闭 P2 和 P3,但不会关闭 P1 — 您也需要关闭 P1。并且您需要查看父进程对管道的处理;它可能也应该关闭它们。