Home

mmap

mmap is a POSIX system call that creates a new mapping in the virtual address space of the calling process. It can map a regular file or device into memory, or create an anonymous mapping that is not backed by any file. Mapped regions behave like arrays and can be accessed via pointers, with the actual I/O performed by the kernel as pages are faulted in or out.

Signature and parameters: void* mmap(void* addr, size_t length, int prot, int flags, int fd, off_t offset). The

Behavior: File-backed mappings can be shared between processes if MAP_SHARED; changes may be written back to

Notes: The offset must be a multiple of the page size, and the mapping length should be

Usage and portability: mmap is standard in POSIX; Windows provides a different API (MapViewOfFile). Performance benefits

addr
hint
is
the
desired
address
or
NULL
to
let
the
kernel
choose.
The
length
is
the
mapping
size;
offset
must
be
a
multiple
of
the
system
page
size.
Prot
flags
specify
allowed
access:
PROT_READ,
PROT_WRITE,
PROT_EXEC,
PROT_NONE.
Flags
include
MAP_SHARED,
MAP_PRIVATE,
MAP_ANONYMOUS.
If
MAP_ANONYMOUS
is
used,
fd
and
offset
are
ignored;
if
not,
fd
refers
to
an
open
file
descriptor.
the
underlying
file,
depending
on
flags.
MAP_PRIVATE
provides
copy-on-write
semantics;
writes
are
not
visible
to
other
processes
nor
written
to
the
file.
Anonymous
mappings
are
not
tied
to
files
and
are
typically
zero-initialized.
On
unmapping
with
munmap,
resources
are
released;
changes
to
a
file-based
mapping
may
be
synchronized
with
the
file
via
msync
or
automatically
on
unmapping
in
some
cases.
at
least
one
page.
The
function
returns
a
pointer
to
the
mapped
area
on
success,
or
MAP_FAILED
on
error
with
errno.
include
zero-copy
I/O
and
efficient
interprocess
communication
via
shared
memory,
but
it
requires
careful
synchronization.
Common
uses
include
loading
large
files
for
random
access
and
implementing
shared
memory
regions.