管道连接两个进程实例

/*该段代码演示怎样创建一个管道链接两个进程。
 *用法: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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值