A process may map files to its address space, thereby creating a 1-to-1
equivalence between the files' data and its corresponding memory-mapped
region. Memory mapping has several uses:
* Dynamic loading -- A program can load executable code sections
dynamically by mapping executable files and shared libraries into
its address space.
* Fast-file I/O -- Ordinary file I/O operations, such as read() and
write(), require the kernel's intermediation; data from the file
is copied to a kernel's buffer rather than directly to the
process. Memory mapping eliminates this intermediary buffering,
thus improving the overall I/O performance.
* Just-in-time compilation -- Memory allocated through memory maps
can be made executable and filled with machine instructions that
are then executed. Utilities that generate code on the fly and
just-in-time compilers use this feature.
* Streamlining file access -- Once you map a file to a memory
region, you access it via pointers, just as you would access the
program's variables and arrays, thus eliminating the need for
fread(), fseek(), fwrite() function calls.
* Memory persistence -- Memory mapping enables processes to share
memory sections that persist independently of a certain process's
Mapping and unmapping
You map memory by using the mmap() system call that is declared in
caddr_t mmap(caddress_t map_address, size_t length,
int protection, int flags, int fd, off_t offset);
The map_address parameter indicates the address to which the memory
should be mapped. A NULL value allows the kernel to pick any address.
The second parameter indicates the number of bytes to map from the
file. The third parameter indicates the types of access allowed to the
PROT_READ the mapped region may be read
PROT_WRITE the mapped region may be written
PROT_EXEC the mapped region may be executed
The fourth parameter indicates various mapping attributes. The
MAP_LOCKED attribute, for instance, guarantees that the mapped region
is never swapped. The fd parameter is a descriptor of the file being
mapped into memory. Finally, offset specifies the position in the file
from which mapping should begin. Offset 0 indicates mapping from the
In the following example, the program maps the first 4 KB of a file
passed whose name is passed as a command line argument:
int main(int argc, char *argv)
void * pregion;
if (fd= open(argv, O_RDONLY) <0)
perror("failed on open");
/*map first 4 kilobytes of fd*/
pregion=mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
/*..access mapped memory*/
The munmap() function unmaps a mapped region.
int munmap(caddr_t addr, int length);
addr is the regions address and length specifies how much of the memory
should be unmapped (you may unmap a portion of a mapped region).