从man
页面
MAP_ANONYMOUS
The mapping is not backed by any file; its contents are initialized to zero. The fd and offset arguments are ignored; however, some implementations require
fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this. The use of MAP_ANONYMOUS in conjunction with
MAP_SHARED is only supported on Linux since kernel 2.4.
使用MAP_ANONYMOUS
的目的是什么?任何一个例子都会很好。还要从哪里映射内存?
它写在man
页面The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is only supported on Linux since kernel 2.4.
如何与其他进程共享与MAP_ANONYMOUS映射的内存?
答案 0 :(得分:27)
匿名映射可以描绘为归零虚拟文件。 匿名映射只是大型,零填充的内存块,可供使用。 这些映射位于堆外部,因此不会导致数据段碎片。
MAP_ANONYMOUS + MAP_PRIVATE:
MAP_ANONYMOUS + MAP_SHARED:
在Linux上,有两种方法可以创建匿名映射:
指定MAP_ANONYMOUS标志并为fd
传递-1 addr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED)
exit(EXIT_FAILURE);
打开/ dev / zero并传递此打开的fd
fd = open("/dev/zero", O_RDWR);
addr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
(此方法通常用于BSD之类的系统,没有MAP_ANONYMOUS标志)
匿名映射的优点:
- 没有虚拟地址空间碎片;取消映射后,内存立即返回系统
- 它们在分配大小,权限方面是可修改的,它们也可以像普通映射一样接收建议
- 每个分配都是一个独特的映射,与全局堆
匿名映射的缺点:
- 每个映射的大小是系统页面大小的整数倍,因此可能导致地址空间的浪费
- 创建和返回映射会产生比预分配堆
如果包含此类映射的程序,分叉进程,则子进程继承该映射。 以下程序演示了这种继承:
#ifdef USE_MAP_ANON
#define _BSD_SOURCE
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
/*Pointer to shared memory region*/
int *addr;
#ifdef USE_MAP_ANON /*Use MAP_ANONYMOUS*/
addr = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (addr == MAP_FAILED) {
fprintf(stderr, "mmap() failed\n");
exit(EXIT_FAILURE);
}
#else /*Map /dev/zero*/
int fd;
fd = open("/dev/zero", O_RDWR);
if (fd == -1) {
fprintf(stderr, "open() failed\n");
exit(EXIT_FAILURE);
}
addr = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
fprintf(stderr, "mmap() failed\n");
exit(EXIT_FAILURE);
}
if (close(fd) == -1) { /*No longer needed*/
fprintf(stderr, "close() failed\n");
exit(EXIT_FAILURE);
}
#endif
*addr = 1; /*Initialize integer in mapped region*/
switch(fork()) { /*Parent and child share mapping*/
case -1:
fprintf(stderr, "fork() failed\n");
exit(EXIT_FAILURE);
case 0: /*Child: increment shared integer and exit*/
printf("Child started, value = %d\n", *addr);
(*addr)++;
if (munmap(addr, sizeof(int)) == -1) {
fprintf(stderr, "munmap()() failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
default: /*Parent: wait for child to terminate*/
if (wait(NULL) == -1) {
fprintf(stderr, "wait() failed\n");
exit(EXIT_FAILURE);
}
printf("In parent, value = %d\n", *addr);
if (munmap(addr, sizeof(int)) == -1) {
fprintf(stderr, "munmap()() failed\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
<强>来源:强>
Linux编程接口
第49章:记忆映射,
作者:Michael Kerrisk
Linux系统编程(第3版)
第8章:内存管理,
作者:Robert Love