【Linux系统编程】无名管道pipe的使用

Linux无名管道pipe的使用

1.函数原型

int pipe(int pipefd[2]);
  • 函数返回值:成功返回 0;失败返回-1;设置error
  • pidfd[0] ; pipefd[1]
  • 管道中,数据读走了,就没有数据
  • pipe函数包含在unistd.h头文件中
  • 如果pipe在读数据的时候,管道中没有数据,则会保持阻塞状态,直到有数据读出

2. pipe实例

  • 使用pipe所要完成的功能为:子进程写数据到管道,父进程读数据并且将内容显示到终端实例程序:
  •   #include <stdio.h>
      #include <string.h>
      #include <unistd.h>
      #include <stdlib.h>
      #include <sys/types.h>
      #include <sys/wait.h>
      
      int main()
      {
          int pipfd[2];
          char writebuf[20]="I have a dream\n";
          char readbuf[20]={0};
      
          if(pipe(pipfd)==-1)
          {   
              printf("failed at create pipe\n");
          }   
          else
          {   
              int forkret=fork();
              if(forkret==0)
              {
                  sleep(3);//用以判断当管道中没有数据,是否会阻塞
                  printf("Here is chailed\n");
                  close(pipfd[0]);
                  write(pipfd[1],writebuf,strlen(writebuf));
                 // exit(0);
              }
              else if(forkret>0)
              {
                  //wait(NULL);
                  printf("Here is father\n");
                  close(pipfd[1]);
                  read(pipfd[0],readbuf,1024);
                  printf("read %s",readbuf);
              }
              else
              {
                  printf("failed fork\n");
              }
          }   
          return 0;
      }
    

  • 程序运行结果:
    在这里插入图片描述
  • 程序在运行时首先进入了父进程,当子进程还没有数据写入到管道时,子进程处于阻塞状态。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值