输入输出重定向问题

想实现 ./pipe args[1] args[2],使其实现管道的功能

if ( pid  == 0 ){ /* parent will exec av[2] */
close(pipe_in[1]); /* parent doesn't write to pipe */
        close(pipe_out[0]);
        dup2(pipe_out[1],1);
dup2(pipe_in[0], 0) ;
        close(pipe_out[1]);
close(pipe_in[0]); /* stdin is duped, close pipe */
       execl("/home/heey/webserver/web5/www/hello", "hello", NULL);
}
      close(pipe_out[1]);
      close(pipe_in[0]);/* child doesn't read from pipe */
      write(pipe_in[1],av[1],strlen(av[1]));
      char c;
      while(read(pipe_out[0],&c,1)>0)
  printf("%c",c);
      close(pipe_out[0]);
      close(pipe_in[1]); /* stdout is duped, close pipe */
    waitpid(pid,&status,0);

父进程从管道pipe_in[1]写端写入数据,而进程中pipe_in[0]重定向到标准输入,即在执行execl时,管道pipe_in里面的内容可以作为hello的标准输入,而不是作为hello的参数,在hello的原代码中加入标准输入就可以读取管道pipe_in的内容,这个当时弄了很久才发现,hello是可以执行的文件,而execl后,即可执行文件hello的输出,输入到管道pipe_out[1]中,因为子进程的标准输出重定向到管道pipe_out的标准输入,再在子进程中读取管道pipe_out[0]的内容即可


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值