Using mmap() for Advanced File I/O - Changing the Protection of a Mapping (
Page 3 of 5 )
POSIX defines the mprotect() interface to allow programs to change the permissions of existing regions of memory:
#include <sys/mman.h>
int mprotect (const void *addr,
size_t len,
int prot);
A call to mprotect() will change the protection mode for the memory pages contained in [addr,addr+len), where addr
is page-aligned. The
prot
parameter accepts the same values as the
prot
given to
mmap()
:
PROT_NONE
,
PROT_READ
,
PROT_WRITE
, and
PROT_EXEC
. These values are not additive; if a region of memory is readable, and
prot
is set to only
PROT_WRITE
, the call will make the region only writable.
On some systems,
mprotect()
may operate only on memory mappings previously created via
mmap()
. On Linux,
mprotect()
can operate on any region of memory.
On success, mprotect() returns 0. On failure, it returns -1
, and sets
errno
to one of the following:
EACCESS
The memory cannot be given the permissions requested by
prot
. This can happen, for example, if you attempt to set the mapping of a file opened read-only to writable.
EINVAL
The parameter
addr
is invalid or not page-aligned.
ENOMEM
Insufficient kernel memory is available to satisfy the request, or one or more pages in the given memory region are not a valid part of the process’ address space.