mmap的使用之两个进程通过映射普通文件实现共享内存通信
2016-05-30 10:13
561 查看
/*-------------map_normalfile1.c-----------*/ #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <unistd.h> typedef struct{ char name[4]; int age; } people; //mmap_normal_file1.c 两个进程通过映射普通文件实现共享内存通信 void main(int argc, char **argv)//map a normal file as shared mem: { int fd,i; people *p_map; char temp; char data[64]; fd = open(argv[1], O_CREAT | O_RDWR | O_TRUNC, 00777); lseek(fd, sizeof(people) * 5 - 1, SEEK_SET); write(fd, "", 1); //把文件映射到共享内存 p_map = (people*)mmap(NULL, sizeof(people) * 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); temp = 'a'; for(i=0;i<10;i++) { temp += 1; sprintf(data, "exe%c", temp); memcpy((*(p_map + i)).name, &data, strlen(data)); (*(p_map + i)).age = 20 + i; } printf("initializeover write finish \n"); sleep(10); munmap(p_map, sizeof(people) * 10); printf("umap ok\n"); }
/*-------------map_normalfile2.c-----------*/ #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> typedef struct { char name[4]; int age; }people; //mmap_normal_file2.c 两个进程通过映射普通文件实现共享内存通信 void main(int argc, char **argv)//map a normal file as shared mem: { int fd, i; people *p_map; fd = open(argv[1], O_CREAT | O_RDWR, 00777); p_map = (people*)mmap(NULL, sizeof(people) * 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); for(i = 0 ; i < 10 ; i++) { printf("read data name=%s age=%d;\n", (*(p_map + i)).name, (*(p_map + i)).age); } munmap(p_map, sizeof(people) * 10); }
#Generated by VisualGDB project wizard. #Note: VisualGDB will automatically update this file when you add new sources to the project. #CMakeList.txt cmake_minimum_required(VERSION 2.7) project(LinuxProject1) set(LIBRARIES_FROM_REFERENCES "") add_executable(mmap_normal_file1 mmap_normal_file1.c) add_executable(mmap_normal_file2 mmap_normal_file2.c) target_link_libraries(mmap_normal_file1 "${LIBRARIES_FROM_REFERENCES}") target_link_libraries(mmap_normal_file2 "${LIBRARIES_FROM_REFERENCES}")
相关文章推荐
- 精彩回顾 | HDG南京站圆满落幕,交流、分享,接地气!
- leetcode validate binary search tree
- java版简易 nc
- iOS 数据库篇8—FMDB数据库队列
- Device is offline
- Beyond Compare 4 crack
- nRF51822外部中断学习总结
- 无约束极值、线性分类器和线性回归基础
- JavaScript学习--Item16 for 循环和for...in 循环的那点事儿
- Android Listview异步动态加载网络图片
- STM32F0xx_TIM基本延时配置详细过程
- 基因数据处理39之mango安装记录
- 微信支付遇到的超级蛋疼的事
- linux centos 和ubuntu 的安装命令
- 猴子吃桃-倒推法
- 文件的编码
- sdau三 1010
- rm -rf 的“幸存者”
- Python3 爬虫(五) -- 单线程爬取我的CSDN全部博文
- backBarButtonItem 颜色/文字修改