linux进程间通讯,(父子进程间)

管道通讯(父读子写)
互斥:任何时刻只能有一个人正在使用某种资源
管道内部自动提供了互斥与同步机制
如果写端关闭,读端就会read返回值0,代表文件结束
如果打开文件的进程退出,文件也会被释放
文件的生命周期随进程
<管道的流式服务>
管道是半双工,就是数据只可以向一个方向流动
匿名管道,适合具有血缘关系的进程进行进程间通讯

read :没有内容挂起
write:没有空间挂起

如若管道没有父进程读,就会读文件错误。
read关闭,一直写,写方(child)被操作系统杀掉,写入无意义

linux实现父子管道通讯的代码如下(父读子写)

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <sys/types.h>                                                                                                                        
  4 #include <sys/wait.h>
  5 #include <string.h>
  6 #include <stdlib.h>
  7 
  8 int main()
  9 {
 10     int fd[2]={0};
 11 
 12     if(pipe(fd)<0) //创建读写的文件窗口
 13     {
 14         printf("pipe error!\n");
 15         return 1;
 16     }
 17 
 18     //printf("fd[0]:%d\n",fd[0]);
 19     //printf("fd [1]:%d\n",fd[1]);
 20     
 21     pid_t id=fork();
 22     if(id==0)
 23     {
 24         //child
 25         close(fd[0]);
 26         const char* str="hello,i am child!";
 27         int count=10;
 28         while(count)
 29         {
 30             write(fd[1],str,strlen(str));
 31             count--;
 32             sleep(1);
 33         }
 34         exit(0);
 35     }
 36 
 37     //father
 38     close(fd[1]);
 39     char buff[64];
 40     while(1)
 41     {
 42         ssize_t s=read(fd[0],buff,sizeof(buff));    //s是实际读到的字节数 读的时候,因为管道里面的互斥,写一个读一个,所以感觉就/有sleep
 43         if(s>0)
 44         {
 45             buff[s]='\0';
 46             printf("child send to father# %s\n",buff);
 47         }
 48         else if(s==0)   //如果写端关闭,读端自动读到0值
 49         {
 50             printf("read file end!\n");
 51             break;
 52         }
 53         else 
 54         {
 55             printf("read error!\n");
 56             break; 
 57         }
 58     }
 59     waitpid(id,NULL,0);
 60     return 0;
 61 }         
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值