【问题标题】:trouble to exec more than 2 pipes in a linux shell simulator (c)在 linux shell 模拟器中执行超过 2 个管道的麻烦(c)
【发布时间】: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 个管道命令,我将非常感激。

【问题讨论】:

    标签: c pipe exec


    【解决方案1】:

    你的问题是,如果你有这样的管道:

    cmd1 | cmd2 | cmd3 | cmd4
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-12-11
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多