mmap() is a POSIX1b function that maps a region of a file into memory. If several processes maps the same or overlapping regions of the same file, they will effectively share the memory. A special case is mmap:ing /dev/zero which results in a new anonymous region each time mapped.

A function that has exited on Unix systems since 4.4 BSD (which was released in the early 90s). I'm not sure exactly when it was added to BSD, but I am sure that 4.3 BSD did not have it. However, given that there was over 5 years time between these two releases, it is likely that it was well-known before that actual release of 4.4 -- for example W. Richard Stevens covers it very completely in Advanced Programming in the Unix Environment, which was written before the release of 4.4 BSD.

It allows a program to map a file (which, on Unix, can also be a hardware device or a psuedo-file like /dev/zero) into the address space of the process.

The mmap function enables a number of powerful programming techniques to be used. Here is just a small sampling of examples:

File access: You can pretend that a file is, instead, a block of RAM, which can make algorithms simpler and faster. For example, GNU grep has an option to use mmap instead of reading the file. To quote the man page for grep:

In some situations, --mmap yields better perfor­mance. However, --mmap can cause undefined behav­ior (including core dumps) if an input file shrinks while grep is operating, or if an I/O error occurs.

Designing a custom memory allocator: In cryptographic applications, it's often useful to ensure that memory is never swapped out to disk. An alternate way to look at this is to make sure that if the VM system ever does swap out your memory, you know where the VM swapped it out to, so you can go overwrite it. This is trivial with mmap.

Drivers: Virtually any kind of device driver needs memory mapping, in order to map device memory into the address space of the driver.

Shared Memory: POSIX-style shared memory is based around mmap and the sem_open function.

I don't think you can really be a Unix C programming expert without knowing about mmap.

Log in or registerto write something here or to contact authors.