Memory Mappings 1023
/* Obtain the size of the file and use it to specify the size of
the mapping and the size of the buffer to be written */
if (fstat(fd, &sb) == -1)
errExit("fstat");
addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (addr == MAP_FAILED)
errExit("mmap");
if (write(STDOUT_FILENO, addr, sb.st_size) != sb.st_size)
fatal("partial/failed write");
exit(EXIT_SUCCESS);
}
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– mmap/mmcat.c
49.3 Unmapping a Mapped Region: munmap()
The munmap() system call performs the converse of mmap(), removing a mapping
from the calling process’s virtual address space.
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.
#include <sys/mman.h>
int munmap(void *addr, size_t length);
Returns 0 on success, or –1 on error