Introduction
mmap
maps a file to a process virtual address space. The file blocks are loaded as needed, in units of the system page size. Each I/O must align with the page size. A block load is handled as a page fault.
mmap()
can provide a private or shared mapping of a region.
mmap() to allocate heap memory
Interesting usage of mmap
is to allocate heap memory in a process.
MAP_ANONYMOUS
or
MAP_ANON
This flag tells the system to create an anonymous mapping, not connected to a file. filedes and offset are ignored, and the region is initialized with zeros.
Anonymous maps are used as the basic primitive to extend the heap on some systems. They are also useful to share data between multiple tasks without creating a file.
On some systems using private anonymous mmaps is more efficient than using malloc
for large blocks. This is not an issue with the GNU C Library, as the included malloc
automatically uses mmap
where appropriate.
Example
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include "assert.h"
#include <string.h>
int main() {
size_t pageSize = getpagesize();
printf("system page size=%zu bytes\n", pageSize);
int fd = open("/tmp/xx", O_RDONLY, 0);
char *region = mmap(NULL, 4*pageSize, PROT_READ|PROT_EXEC, MAP_ANON|MAP_PRIVATE, fd, 0);
assert(region != MAP_FAILED);
memset(region, 'y', pageSize);
char read_buf[4096];
memcpy(read_buf, region, pageSize);
printf("char at 0 offset = %c\n", read_buf[0]);
// cleanup
int rc = munmap(region, 4*pageSize);
assert(rc == 0);
close(fd);
return 0;
}
References
- https://medium.com/i0exception/memory-mapped-files-5e083e653b1
- https://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html#Memory_002dmapped-I_002fO
Written with StackEdit.