A process's memory regions may be paged, or swapped, to a disk file
when RAM has become scarce. The virtual memory management system is
responsible for this swapping. In most cases, a process doesn't care
about the exact, physical location of a certain memory page. However,
the latency caused by the kernel's paging of memory back into RAM may
be unacceptable to time-sensitive applications.
To avoid this latency, a process can lock specific memory regions in
RAM and thus ensure that they aren't paged to a disk file. Only
processes with root permissions are allowed to lock memory. The total
amount of memory that a process can lock shall not exceed the
The memory locking interfaces are declared in . This header
file declares the following functions:
int mlock(caddr_t addr, size_t length);
mlock() locks length bytes starting at address addr. Since Linux can
only lock entire pages, the beginning and the end of the locked region
are "rounded" to fit into page boundaries. Consequently, the locked
block may be equal or larger than length. When mlock() returns, all the
pages in the specified range have been locked in RAM.
int mlockall(int flags);
To lock the entire address space of a process, you call the mlockall()
function. The flags argument may be one of the following constants or
both of them combined with the bitwise OR operator:
* MCL_CURRENT - all the pages in the process's address space are
locked into RAM.
* MCL_FUTURE - all future pages added to the process's address
space would be locked into RAM.
To unlock memory, you call munlock():
int munlock(caddr_t addr, size_t length);
The munlock() function takes the same arguments as mlock() and unlocks
all the pages in the indicated region.
To lock all the locked regions at once, call munlockall(). This
function has the following prototype:
Locking the same page multiple times has the same effect as locking it
once. Regardless of the number of lock operations, a single call to
munlock() will unlock the specified region.
In last week's newsletter, I made a typo in the final section. The call
to the goodday() function through a pointer should read pgoodday(), not
goodday(). Likewise, the second technical note should read as follows:
pgoodday(); /* #2 call library's function through the pointer
2. When you call a function through a pointer, you use the pointer
as if it were the function's name. However, the following form
is also legal, albeit antiquated and perhaps less readable: