博客
关于我
15LinuxC进程间通信之mmap无血缘进程间通信
阅读量:238 次
发布时间:2019-03-01

本文共 1781 字,大约阅读时间需要 5 分钟。

1 mmap无血缘进程间通信

1)写文件:

#include 
#include
#include
#include
#include
#include
#include
#include
typedef struct Student{ int id; char name[64]; int age;}student;void sys_err(cost char *str){ perror(std); exit(1);}int main(void){ struct student stu = { 1, "xiaoming", 18}; struct student *p = NULL; int fd; fd = open("test_map", O_RDWR | O_CREAT | O_TRUNC, 0664); if(fd == -1){ sys_err("open failed."); } ftruncate(fd, sizeof(stu)); p = mmap(NULL, sizeof(stu), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { sys_err("mmap error"); } close(fd); while (1){ memcpy(p, &stu, sizeof(stu)); stu.id++; } munmap(p, sizeof(stu)); return 0;}

2)读文件:

#include 
#include
#include
#include
#include
#include
#include
#include
typedef struct Student{ int id; char name[64]; int age;}student;void sys_err(cost char *str){ perror(std); exit(1);}int main(void){ struct student stu; struct student *p = NULL; int fd; fd = open("test_map", O_RDONLY, 0664); if(fd == -1){ sys_err("open failed."); } //ftruncate(fd, sizeof(stu)); p = mmap(NULL, sizeof(stu), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (p == MAP_FAILED) { sys_err("mmap error"); } close(fd); while (1){ //memcpy(p, &stu, sizeof(stu)); //stu.id++; printf("id=%d, name=&s, age=%d\n", p->id, p->name, p->age); } munmap(p, sizeof(stu)); return 0;}

结果如下,注意,由于我们开辟的映射区刚好是一个stu的大小,所以前面可能因为读得慢导致被覆盖掉几个student类型的数据。

在这里插入图片描述

2 多个读写mmap

首先:将上面的写程序的open,去掉O_TRUNC截断标志,保证多个进程写时文件可以追加。

1)多个写,一个读,可以看到,mmap是可以重复读取内容的,因为文件内容不变,而管道pipe,fifo只能读取一次,读走就没有了。
在这里插入图片描述

3 总结

  • 1)mmap的数据可以重复读取,而pipe,fifo只能读取一次。
  • 2)mmap能在无血缘的进程间通信根本原因是因为有共同的映射区。pipe,fifo因为有共同的管道。当然有血缘关系的mmap和匹配,fifo也可以这样解释。

转载地址:http://osfv.baihongyu.com/

你可能感兴趣的文章
Nginx多域名,多证书,多服务配置,实用版
查看>>
nginx如何实现图片防盗链
查看>>
Nginx学习总结(10)——Nginx前后端分离将多个请求转发到多个Tomcat,负载均衡反向代理
查看>>
Nginx学习总结(11)——提高Nginx服务器的安全性,稳定性和性能的12种技巧
查看>>
Nginx学习总结(12)——Nginx各项配置总结
查看>>
Nginx学习总结(13)——Nginx 重要知识点回顾
查看>>
Nginx学习总结(14)——Nginx配置参数详细说明与整理
查看>>
Nginx学习总结(15)—— 提升 Web 应用性能的十个步骤
查看>>
Nginx学习总结(1)——Nginx入门简介
查看>>
Nginx学习总结(2)——Nginx手机版和PC电脑版网站配置
查看>>
Nginx学习总结(3)——Nginx配置及应用场景之高级配置
查看>>
Nginx学习总结(4)——负载均衡session会话保持方法
查看>>
Nginx学习总结(5)——Nginx基本配置备忘
查看>>
Nginx学习总结(7)——Nginx配置HTTPS 服务器
查看>>
Nginx学习总结(8)——Nginx服务器详解
查看>>
Nginx学习总结(9)——前端跨域问题解决
查看>>
nginx学习笔记002---Nginx代理配置_案例1_实现了对前端代码的方向代理_并且配置了后端api接口的访问地址
查看>>
nginx学习笔记003---Nginx代理配置_注意,在Windows中路径要用/
查看>>
Nginx学习笔记(一) Nginx架构
查看>>
nginx学习路线
查看>>