System Interface Guide

Creating and Using Mappings

mmap(2) establishes a mapping of a named file system object (or part of one) into a process address space. It is the basic memory management function and it is very simple. First open(2) the file, then mmap(2) it with appropriate access and sharing options and go about your business.

The mapping established by mmap(2) replaces any previous mappings for specified address range.

The flags MAP_SHARED and MAP_PRIVATE specify the mapping type, and one of them must be specified. MAP_SHARED specifies that writes modify the mapped object. No further operations on the object are needed to make the change. MAP_PRIVATE specifies that an initial write to the mapped area creates a copy of the page and all writes reference the copy. Only modified pages are copied.

A mapping type is retained across a fork(2).

The file descriptor used in a mmap(2) call need not be kept open after the mapping is established. If it is closed, the mapping remains until the mapping is undone by munmap(2) or be replacing it with a new mapping.

If a mapped file is shortened by a call to truncate, an access to the area of the file that no longer exists causes a SIGBUS signal.

Mapping /dev/zero gives the calling program a block of zero-filled virtual memory of the size specified in the call to mmap(2). The following code fragment demonstrates a use of this to create a block of scratch storage in a program, at an address that the system chooses.

	int fd;
 caddr_t result;

 if ((fd = open("/dev/zero", O_RDWR)) == -1)
 	return ((caddr_t)-1);
 result = mmap(0, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
 (void) close(fd);

Some devices or files are useful only if accessed by mapping. An example of this is frame buffer devices used to support bit-mapped displays, where display management algorithms function best if they can operate randomly on the addresses of the display directly.