0
点赞
收藏
分享

微信扫一扫

linux 有名管道进程间的通信

北邮郭大宝 2022-04-27 阅读 79
linux

目录

一 回顾

实验 ps aux | grp “bash”
 1 ps aux :父进程 grp “bash”:子进程 但是不能直接通信 
 2 需要把 父进程 重定向为管道 也就是换了输出位置 
 3 并且父进程从main 开始 ./a。out 打印的是 子进程 excpl 设定的信息 中的 参数的数据 而没有参数命令
4  ps aux | grp “bash” 才会出现 子进程读取父进程的东西  

二 有名管道

操作目录

因为是进程通信  所以在 ipc 目录下操作 

使用场景

没有血缘关系的 进程通信 

特点

伪文件 :不占磁盘空间
半双工通信 双方都可发送或者接收 只能在摸个时刻 

1 有名 管道 创建

在这里插入图片描述
形参

形参一:绝对路径
形参二:文件权限
#include<sys/stat.h>
#include<sys/types.h>

 int main()
 {
     int fifos;

     fifos=mkfifo("\home\ycy\ipc\myfifo",0755);

     if(fifos==-1)
     {
     printf("myfifo is error\n");
     return -1;
     }
     printf("myfifo is sueecss\n");
          
   return 0;
 }
 

在这里插入图片描述

p :管道类型的 文件 并且颜色加重了 

三 有名管道进程间的通信

在这里插入图片描述
在什么时候才会参数 fifo 呢

1 mdfifo 在创建 并不会产生fifo 而是会产生一个结点 结点指向 缓存区 但是缓存区的大小为零 
(队列的原因 流动性)
2 当使用open 函数时 管道才会产生新建的fifo函数 

1 直接撸代码

在这里插入图片描述

返回值为读取的字节数

#include<sys/stat.h>
#include<sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

 int main()
 {
     int fifos;
     int fd;
     int rs;
     char readbuff[128]={0};
     
     fifos=mkfifo("/home/ycy/ipc/myfifo",0755);

     if(fifos==-1)
     {
     printf("myfifo is error\n");
     return -1;
     }
     printf("myfifo is sueecss\n");
     
      fd=open("/home/ycy/ipc/myfifo",O_RDONLY);
      
      if(fd<0)
      {
          printf("open is error\n");
          perror("why");   
             return -1;  
      } 
      printf("open is sueecss\n");
     
      rs=read(fd,readbuff,128);
      
      printf("read is %s\n",readbuff);
      printf("read can is %d\n",rs);
       close(fd);
     
      return 0;
 }

在这里插入图片描述

为啥一直读出不了数据呢 因为管道没有内容 
所以是缺了“写入”函数 

在这里插入图片描述

#include<sys/stat.h>
#include<sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

 int main()
 {
     int fifos;
     int fd;
     int ws;
     char  *str="yi ding ke yi zuo chu lai de";
     
      fd=open("/home/ycy/ipc/myfifo",O_WRONLY);
      
      if(fd<0)
      {
          printf("open is error\n");
          perror("why");   
             return -1;  
      } 
      printf("open is sueecss\n");
   
      write(fd,str,strlen(str));
      
       close(fd);
     
      return 0;
 }

开另外的终端 编译 这个函数 

在这里插入图片描述

一定 成功  !!!!!!!!!!!
举报

相关推荐

0 条评论