The munmap() system call performs the converse of mmap(), removing a mapping from the calling process’s virtual address space.
#include <sys/mman.h>
int munmap
(void *addr, size_t length);
Returns 0 on success, or -1 on error
The addr argument is the starting address of the address range to be unmapped. It must be aligned to a page boundary. (SUSv3 specified that addr must be page-aligned. SUSv4 says that an implementation may require this argument to be page-aligned.)
The length argument is a nonnegative integer specifying the size (in bytes) of the region to be unmapped. The address range up to the next multiple of the system page size will be unmapped.
Commonly, we unmap an entire mapping. Thus, we specify addr as the address returned by a previous call to mmap(), and specify the same length value as was used in the mmap() call. Here’s an example:
addr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (addr == MAP_FAILED) errExit("mmap"); /* Code for working with mapped region */ if (munmap(addr, length) == -1) errExit("munmap");
Alternatively, we can unmap part of a mapping, in which case the mapping either shrinks or is cut in two, depending on where the unmapping occurs. It is also possible to specify an address range spanning several mappings, in which case all of the mappings are unmapped.
If there are no mappings in the address range specified by addr and length, then munmap() has no effect, and returns 0 (for success).
During unmapping, the kernel removes any memory locks that the process holds for the specified address range. (Memory locks are established using mlock() or mlockall(), as described in Section 50.2.)
All of a process’s mappings are automatically unmapped when it terminates or performs an exec().
To ensure that the contents of a shared file mapping are written to the underlying file, a call to msync() (Synchronizing a Mapped Region: msync()) should be made before unmapping a mapping with munmap().