Memory mapping

By Danny Kalev, ITworld |  How-to

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
as follows:

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
mapped region:

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.

Join us:






Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Ask a Question