【问题标题】:Pipe() fork() and execPipe() fork() 和执行
【发布时间】:2011-06-02 20:31:58
【问题描述】:

我尝试在迷你外壳中添加管道。 我很困惑,当我输入 ls |排序,没有显示,我不明白为什么:

int fd[2];
if (tube == 1){

    int pipeling = pipe(fd);
    if (pipeling == -1){
        perror("pipe") ;
    }
}


    tmp = fork();               //FORK A

    if (tmp < 0){
        perror("fork");
        continue;
    }

    if (tmp != 0) {                 //parent
                while(wait(0) != tmp) ;
                continue ;
    }

    if (tube == 1) {                //there is a pipe

    if (tmp != 0){                  //parent A
        close(fd[1]);
    }

        if (tmp == 0){              //Child A                     
            close(fd[0]);
            dup2(fd[1], 1);
            close(fd[1]);
            execv(mot[0], mot);
    }

    int tmp2 = fork() ;             //FORK B

    if (tmp2 != 0) {                //Parent B
        close(fd[0]);
        while(wait(0) != tmp2) ;
        continue ;
    }

    if (tmp2 == 0){                 //Child B
        close(fd[1]);
        dup2(fd[0], 0);
        close(fd[0]);
        execvp(mot[1], mot);

    }
}

我已阅读有关此的所有主题,但它不起作用。 你能帮帮我吗?

编辑:第二个代码,我尝试改变结构。

谢谢。

【问题讨论】:

  • 检查系统调用是否有错误 - 您至少在某个时刻重复了一个已关闭的 fd。什么是“摩”?我的猜测是您的 execvp 参数不正确。
  • @pilcrow,我已经编辑了代码,mot 是命令行上给出的命令。
  • 在您的链接中,他们使用了两对文件描述符,我不明白为什么,fd[2] 应该不起作用?

标签: c shell unix fork pipe


【解决方案1】:

如果execvp 成功,则不会到达第二个fork,因为后者应该替换进程的图像并停止执行当前代码。

你必须重组你的程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多