linux编程——管道操作

#include <iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/fcntl.h>
#include<unistd.h>
#include<cstring>
#include<sys/wait.h>
using namespace std;

int main(int argc, char *argv[])
{
   int result=-1;
   int fd[2],nbyte;

   pid_t pid;
   char  str[]="hello,world";
   char str_recv[100];
     result=pipe(fd);
   int read_pipe=fd[0];        //这里有个坑,一开始我把读管道设置成了fd[1],写设置成了fd[0]
   cout<<"read_pipe is  "<<read_pipe<<endl;
   int write_pipe=fd[1];     //管道的设置有严格的顺序,fd[0]才是读   fd[1]才是写
    cout<<"write_pipe is  "<<write_pipe<<endl;


   pid=fork();  //创建一个进程
   if(pid==-1)
   {
       perror("pid:error");
   }

   if(pid==0)   //子进程
   {
       cout<<"11111"<<endl;
       close(read_pipe);
       cout<<"str is "<<str<<endl;
       result=write(write_pipe,str,strlen(str));
       cout<<"write result value is "<<result<<endl;

       return 0;

   }
   if(pid>0)  //父进程
   {
         wait(NULL);    //等待子进程结束
       close(write_pipe);
       memset(&str_recv,0,sizeof(str_recv));
       nbyte=read(read_pipe,str_recv,sizeof(str_recv));
       cout<<"recv "<< nbyte  <<" data,data is text :  "<<str_recv <<endl;
   }
   return 0;

}

ps:当管道的写端没有关闭时,写请求的字节数目大于阈值PIPE_BUF(在include/linux/limits.h中可以查看),写操作的返回值是管道中目前的数据字节数。如果请求的字节数(读管道)不大于PIPE_BUF,则返回管道中的现有字节数(管道中数据量小于请求数据量),或者返回请求的字节数(管道中数据量不小于请求的数据量)

 

当写入的数据大于128K时,缓冲区的数据将被持续写入管道,如果没有进程读取,则会一直阻塞

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值