Unix-Linux编程实践教程——pipe

这个demo还是很有意思的,关于重定向和管道结合的很好,也很清晰的展示了进程之间通过管道去通信的原理。

//
// Created by Jimmy on 3/31/20.
//

#include <stdio.h>
#include <unistd.h>
#include <cstdlib>

#define oops(m,x) {perror(m);exit(x);}

int main(int ac, char ** av)
{
    int thepipe[2], newfd, pid;

    if(ac != 3){
        fprintf(stderr, "usage: pipe cmd1 cmd2\n");
        exit(1);
    }

    if(pipe(thepipe) == -1)
        oops("Cannot get a pipe", 1);

    if((pid == fork()) == -1)
        oops("Cannot fork", 2);

    /* parent read from pipe */
    if(pid > 0){
        close(thepipe[1]);

        if(dup2(thepipe[0], 0) == -1)
            oops("could not redirect stdin", 3);

        close(thepipe[0]);
        execlp(av[2], av[2], NULL);
        oops(av[2], 4);
    }

    /* child execs av[1] and writes into pipe */
    else{
        close(thepipe[0]);

        if(dup2(thepipe[1], 1) == -1)
        oops("could not redirect stdout", 4);

        close(thepipe[1]);
        execlp(av[1], av[1], NULL);
        oops(av[1], 5);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章