管道连接两个进程实例

来源:互联网 发布:r语言数据框加一列 编辑:程序博客网 时间:2024/06/07 22:04
/*该段代码演示怎样创建一个管道链接两个进程。
 *用法:pipe command1 command2
 *效果:command1|command2
 *
 */
#include <stdio.h>
#include <unistd.h>
#define oops(m,x)  {perror(m);exit(x);}

main(int ac ,char **av)
{    int thepipe[2];
    int    newfd;
    int    pid;
    
    if(ac!=3)
    {
        fprintf(stderr,"usage:pipe cmd1 cmd2/n");
        exit (1);
    }
    //创建一个管道
    if(pipe(thepipe)==-1)
    oops("create pipe failed!",1);
    //创建一个进程
    if((pid=fork())==-1)
    oops("cannot fork",2);
    //父进程里从管道接受子进程来的运行结果作为操作对象
    if(pid>0)
    {
    close(thepipe[1]);
    newfd=dup2(thepipe[0],0);
    if(newfd==-1)
    oops("could not redirect stdin.",3);
    
    close(thepipe[0]);
    execlp(av[2],av[2],NULL);//av[2]从stdin(thepipe[0])读取数据
    oops(av[2],4);
    }
    //子进程把运行结果添加到管道,传给父进程
    close(thepipe[0]);
    
    if(dup2(thepipe[1],1)==-1)
    oops("cannot redirect stdout",5);
    close(thepipe[1]);
    execlp(av[1],av[1],NULL);//将av[1]的运行结果->stdout(thepipe[1])
    oops(av[1],6);
}