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

From Wikibooks, open books for an open world
Jump to: navigation, 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.

Syntax[edit]

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

Parameter[edit]

addr : the starting address of memory for witch access is to changed.
len  : the length of address range in byte.
prot : ptot may be PROT_NONE or PROT_READ or PROT_WRITE or PROT_EXEC.

each of it has a special meaning

  • PROT_NONE  : the memory can not be assessed 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.

Errors[edit]

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

  • EACCES
  • EAGAIN
  • EINVAL
  • ENOMEM
  • ENOMEM
  • ENOTSUP

Return values[edit]

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

External links[edit]