博客
关于我
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/

你可能感兴趣的文章
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>
Multisim中555定时器使用技巧
查看>>
MySQL CRUD 数据表基础操作实战
查看>>
multisim变压器反馈式_穿过隔离栅供电:认识隔离式直流/ 直流偏置电源
查看>>
mysql csv import meets charset
查看>>
multivariate_normal TypeError: ufunc ‘add‘ output (typecode ‘O‘) could not be coerced to provided……
查看>>
MySQL DBA 数据库优化策略
查看>>
multi_index_container
查看>>
mutiplemap 总结
查看>>
MySQL Error Handling in Stored Procedures---转载
查看>>
MVC 区域功能
查看>>