Notes on Memory Mapped Files using mmap

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

Written with StackEdit.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.