linux下使用mmap实现进程间共享内存

linux下的mmap函数是把文件内容映射到一块内存(准确的说是虚拟内存)上,可以把对文件的操作转为对内存的操作,从而可以避免很多lseek()与read()、write()操作,非常适合于操作大文件或者频繁访问的文件。mmap一般的用途有:

1.将某个真实的文件读入内存,可以频繁读写,在必要的时候写回磁盘

2.各进程间可以共享映射区域

下面这个例子是实现父子进程间共享内存。
#include
#include
#include
#include
#include
#include
#include

typedef struct {
char name[10];
int age;
} person;

int main(){
int i;
person *p_map;
int size;
size = 10*sizeof(person);
p_map=(person*)mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);

if(fork() == 0){

sleep(2);

for(i=0;i<10;i++){ printf("child read: the %d person %s's age is %dn", i+1,(*(p_map+i)).name , (*(p_map+i)).age); } (*p_map).age = 100; munmap(p_map, size); return 0; } for(i=0;i<10;i++){ sprintf( (*(p_map+i)).name, "name%d", i); (*(p_map+i)).age=20+i; } sleep(5); printf("parent read: the first person's age is %dn", (*p_map).age); munmap(p_map, size); return 0; }[/code] 执行结果: [code lang="c"][baoniu@s0001 network]$ ./a.out child read: the 1 person name0's age is 20 child read: the 2 person name1's age is 21 child read: the 3 person name2's age is 22 child read: the 4 person name3's age is 23 child read: the 5 person name4's age is 24 child read: the 6 person name5's age is 25 child read: the 7 person name6's age is 26 child read: the 8 person name7's age is 27 child read: the 9 person name8's age is 28 child read: the 10 person name9's age is 29 parent read: the first person's age is 100[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注