博客
关于我
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高频面试题
查看>>
MySQL高频面试题的灵魂拷问
查看>>
MySQL(1)的使用 | SQL
查看>>
MySQL(2)DDL详解
查看>>
MySQL(3)DML详解
查看>>
MySQL(4)运算符 | 关联查询详解
查看>>
MySQL(5)条件查询 | 单行函数 | 事务详解
查看>>
Mysql,group by分组查询、order by排序查询、join连接查询、union联合查询
查看>>
Mysql,sql文件导入和导出
查看>>
MYSQL:int类型升级到bigint,对PHP开发语言影响
查看>>
Mysql:mysql 5.X 报错 ERROR 1193 (HY000): Unknown system variable ‘validate_password_length‘
查看>>
MySQL:MySQL执行一条SQL查询语句的执行过程
查看>>
Mysql:SQL性能分析
查看>>
mysql:SQL按时间查询方法总结
查看>>
MySQL:什么样的字段适合加索引?什么样的字段不适合加索引
查看>>
MySQL:判断逗号分隔的字符串中是否包含某个字符串
查看>>
MySQL:某个ip连接mysql失败次数过多,导致ip锁定
查看>>
MySQL:索引失效场景总结
查看>>
Mysql:避免重复的插入数据方法汇总
查看>>
MyS中的IF
查看>>