syscalls

mprotect() — Linux system interface

Change access protections of pages covering a region. The address must be aligned to a page boundary. PROT_NONE disallows access; PROT_READ and PROT_WRITE request respective permissions. Architecture and mapping attributes affect exact permissions. Violating protections may cause SIGSEGV; the example never attempts a prohibited access. EINVAL can indicate unaligned start; EACCES may indicate incompatible permissions; ENOMEM may indicate unmapped pages or mapping limits. Do not use this to weaken executable-memory protections. Coordinate protection changes across threads. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. Linux-specific interface or flags; examples target Linux/glibc on x86_64. These are libc-facing signatures, not raw architecture-specific syscall ABIs.

Formal Syntax & Structure

linux syntaxlinux
#include <sys/mman.h>int mprotect(void *addr, size_t len, int prot);

Parameters & Attributes

NameTypeDescription
addrvoid *Page-aligned start.
lensize_tLength in bytes.
protintRequested protection flags.

Return Value

int

0 on success. On failure, returns -1 and sets errno.

Working Example

Example Snippetlinux
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/mman.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \    fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \    return EXIT_FAILURE; \} } while (0)
int main(void){    long page = sysconf(_SC_PAGESIZE);    CHECK(page > 1);    unsigned char *m = mmap(NULL, (size_t)page, PROT_READ | PROT_WRITE,                            MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);    CHECK(m != MAP_FAILED);    m[0] = 3;    CHECK(mprotect(m + 1, (size_t)page - 1, PROT_READ) == -1 && errno == EINVAL);    CHECK(mprotect(m, (size_t)page, PROT_READ) == 0);    CHECK(m[0] == 3);    CHECK(mprotect(m, (size_t)page, PROT_READ | PROT_WRITE) == 0);    m[0] = 9;    CHECK(m[0] == 9);    CHECK(munmap(m, (size_t)page) == 0);    puts("unaligned EINVAL; read-only then read-write; cleanup");    return EXIT_SUCCESS;}
Linux Reference