C Programming/POSIX Reference/sys/mman.h/mprotect

From Wikibooks, open books for an open world
Jump to navigation Jump to search

In Unix-like operating systems, mprotect() is a POSIX system call for controlling memory protections. It sets protection for memory mapping. The function mprotect changes the access protection specified by the prot .
In the word 'mprotect', 'm' stands for memory and 'protect' for protection so, mprotect basically stands for memory protection. mprotect() is a protecting kind of a function. It's working is based on prot. Prot is just a parameter. The proction to access is provided by mprotect as specified by prot.Prot is the one which decide what kind of access is permitted. The access can be of just read, write, execute or even some combinations. However, the argurment to the parameter prot set compulsarily to PROT_READ or one or more of PROT_READ, PROT_EXEC. and PROT_WRITE. Access to the one's not specified by prot is also permitted; But the thing is different in case of PROT_WRITE and PROT_NONE.It is not permitted for write to succed where PROT_WRITE isn't set.Also access is not permitted where PROT_NONE is alone set without any other.

Following values of prot can be implemented:- PROT_NONE, PROT_READ, PROT_WRITE, and the inclusive OR of PROT_READ and PROT_WRITE

If mprotect fails and the error is not EINVAL then it indicates change in protection in the range(addr, addr + len).

Header file[edit]

To use the mprotect function one need to include 'sys/mman.h' header file.


int mprotect(void *addr, size_t len, int prot);


addr : the starting address of memory range for which protection will begin.
len : the length of the protected address range in bytes.
prot : protection flag which may be PROT_NONE or a bitwise-or combination of PROT_READ, PROT_WRITE, and PROT_EXEC.

Each protection flag has a special meaning:

  • PROT_NONE : the memory can not be accessed in any way.
  • PROT_READ : the data of memory can be read.
  • PROT_WRITE : data can be modified by writing to it.
  • PROT_EXEC : the data of memory can be executed.


Following are the common errors due to which mprotect() function will fail if:-


Return values[edit]

Upon successful completion, mprotect() returns 0. Otherwise, it returns -1 and sets errno to indicate the error.

External links[edit]