Memory locking (mlock)
mlock keeps the pages intersecting a process address range resident in RAM while the memory lock applies.
Successful mlock populates the range; Linux mlock2 with MLOCK_ONFAULT instead locks currently resident pages and locks others when faults populate them. Resource limits and permissions apply. [1]
Locks are not inherited across fork, and later writes can incur copy-on-write faults. Unmapping, exec and process exit remove the relevant locks. Locking does not exclude RAM from suspend-to-disk images. [1]
MAP_LOCKED is weaker: mmap may succeed despite incomplete prefaulting. [2]
Residency is not synchronization: msync propagates shared file-mapping changes to the filesystem. MS_INVALIDATE can fail with EBUSY for a locked range; this is not a media-error diagnosis. [3]
Relations
- related
- Memory-mapped file, msync, cachestat
Advantages
- Can keep a selected working range resident without locking the entire address space.
Limitations
- Does not make file updates durable or transactional.
- On-fault locking is not proof that every page has already been populated.
Citations
- Linux man-pages: mlock(2), residency, on-fault locking and lifetime
- Linux man-pages: mmap(2), MAP_LOCKED prefault limitations
- Linux man-pages: msync(2), synchronization and locked-range invalidation
Sources & caveats
- Primary API documentation reviewed 2026-11-14; Linux-specific mlock2 behavior is distinguished from mlock. No latency, swap or power-loss experiment performed.