Linux 匿名 mmap
匿名映射:
#include <sys/mman.h>
void *mmap(void *addr, size_t length, int prot, int flags,int fd, off_t offset);
int munmap(void *addr, size_t length);
在调用mmap函数时候,在flags
参数那里,设置MAP_ANON
,并在fd参数那里设置-1
.
因为没有实体文件, 匿名映射不能实现无血缘关系的进程间通通信. 下面是一个父子通信,并且使用struct
进程内存映射的实例:
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
typedef struct _person {
char name[128];
int age;
} Person;
int main() {
int length = sizeof(Person);
Person *person = (Person *)mmap(NULL, length, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANON, -1, 0);
if (person == MAP_FAILED) {
perror("mmap");
return -1;
}
pid_t pid = fork();
if (pid == 0) {
sprintf(person->name, "brownfeng");
person->age = 18;
printf("child:person.name=%s, person.age=%d\n", person->name, person->age);
sleep(3);
printf("child:person.name=%s, person.age=%d\n", person->name, person->age);
} else if (pid > 0) {
sleep(1);
printf("parent:person.name=%s, person.age=%d\n", person->name, person->age);
sprintf(person->name, "brownfeng -- change");
person->age = 100;
printf("parent:person.name=%s, person.age=%d\n", person->name, person->age);
wait(NULL);
}
munmap(person, sizeof(person));
return 0;
}
网友评论