c - Pipe() fork() 和 exec

标签 c shell unix fork pipe

我尝试在迷你 shell 中添加管道。 我很困惑,当我输入 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);

    }
}

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

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

谢谢。

最佳答案

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

你必须重组你的程序。

关于c - Pipe() fork() 和 exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6220055/

相关文章:

c - 以二维数组为参数的函数

c - 使用 sprintf 的读写系统调用

regex - 如何从 bash 脚本关闭所有不运行任何内容或 iPython 的终端

linux - bash 脚本,第 30 行 : syntax error: unexpected end of file

shell - 在 pig 中执行本地 shell 脚本命令

linux - 如何在 shell 脚本中的 SCP 命令中附加变量?

C 指针 : Assignment from incompatible pointer type

c - 如何调用这个函数来进行字符串查找,然后将结果打印到屏幕上?

linux - Netgem n5200(或其他)-如何进入linux操作系统层?

bash - "kill -INT $pid"不会终止进程,但 ctrl+c 会