麻烦在linux shell模拟器中执行两个以上的管道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 [command index]是要执行的命令。如果有人可以帮助我找到一种执行两个以上管道命令的方法,我将不胜感激。

解决方法

您的麻烦是,如果您有以下管道:

cmd1 | cmd2 | cmd3 | cmd4

(通过管道P1,P2,P3连接),然后在您处理cmd3时,父进程已打开P1,P2和P3,子进程也已打开。您的子代码会仔细关闭P2和P3,但不会关闭P1-您也需要关闭P1。而且,您需要查看父流程对管道的处理方式。它可能也应该关闭它们。