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

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

mmap无血缘进程间通信

1. 写文件

#include 
#include
#include
#include
#include
#include
#include
#include
typedef struct Student { int id; char name[64]; int age;} student;void sys_err(const char *str) { perror(str); 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(const char *str) { perror(str); 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."); } 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) { 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. 总结

  • mmap允许数据重复读取,而pipefifo只能读取一次。
  • mmap无血缘进程间通信的根本原因是共享相同的映射区,而pipefifo则依赖于共享的管道。从这个角度来看,fifo也可以看作是无血缘通信的一种实现方式。

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

你可能感兴趣的文章
Objective-C实现euclidean distance欧式距离算法(附完整源码)
查看>>
Objective-C实现Euclidean GCD欧几里得最大公约数算法(附完整源码)
查看>>
Objective-C实现euclideanDistance欧氏距离算法(附完整源码)
查看>>
Objective-C实现euler method欧拉法算法(附完整源码)
查看>>
Objective-C实现eulerianPath欧拉路径算法(附完整源码)
查看>>
Objective-C实现EulersTotient欧拉方程算法(附完整源码)
查看>>
Objective-C实现eval函数功能(附完整源码)
查看>>
Objective-C实现even_tree偶数树算法(附完整源码)
查看>>
Objective-C实现Exceeding words超词(差距是ascii码的距离) 算法(附完整源码)
查看>>
Objective-C实现extended euclidean algorithm扩展欧几里得算法(附完整源码)
查看>>
Objective-C实现Factorial digit sum阶乘数字和算法(附完整源码)
查看>>
Objective-C实现factorial iterative阶乘迭代算法(附完整源码)
查看>>
Objective-C实现factorial recursive阶乘递归算法(附完整源码)
查看>>
Objective-C实现factorial阶乘算法(附完整源码)
查看>>
Objective-C实现Fast Powering算法(附完整源码)
查看>>
Objective-C实现fenwick tree芬威克树算法(附完整源码)
查看>>
Objective-C实现FenwickTree芬威克树算法(附完整源码)
查看>>
Objective-C实现fft2函数功能(附完整源码)
查看>>
Objective-C实现fibonacci斐波那契算法(附完整源码)
查看>>
Objective-C实现FigurateNumber垛积数算法(附完整源码)
查看>>