ADVERTISEMENT
Responsive Ad Unit • Systems Architecture & Low-Level Engineering

Memory Mappings

Memory mapping allows a file or device to be mapped directly into a process's virtual address space. Instead of using repeated read() and write() system calls, a program can access mapped memory using ordinary pointer operations.

Learning Objectives

  • Understand memory mapping.
  • Learn virtual memory concepts.
  • Study mmap().
  • Study munmap().
  • Understand protection flags.
  • Understand mapping flags.

1. What is Memory Mapping?

Memory mapping is a mechanism that maps a file or device into a process's virtual address space. Once mapped, the application accesses the mapped region as normal memory without explicitly calling read() or write() for every access.

2. Advantages of Memory Mapping

Advantage Description
Efficient File Access Access file contents directly through memory.
Reduced System Calls Fewer read() and write() operations.
Shared Memory Multiple processes can share mapped regions.
Demand Paging Pages are loaded as needed by the operating system.
Large File Support Efficient handling of large files.

3. Memory Mapping Workflow

Application ↓ Open File ↓ mmap() ↓ Virtual Address Space ↓ Read / Write Memory ↓ munmap() ↓ Close File

4. Virtual Memory Overview

Every process executes within its own virtual address space. Memory mapping creates a relationship between a region of this virtual address space and a file or device managed by the kernel.

5. mmap()

The mmap() function creates a mapping between a file (or device) and a region of virtual memory.

#include <sys/mman.h> void *mmap( void *addr, size_t length, int prot, int flags, int fd, off_t offset);

6. Function Parameters

Parameter Description
addr Requested mapping address (or NULL).
length Number of bytes to map.
prot Memory protection flags.
flags Mapping options.
fd File descriptor.
offset File offset where mapping begins.

7. Return Value

Return Description
Valid Address Memory mapping created successfully.
MAP_FAILED Mapping failed (check errno).

8. munmap()

The munmap() function removes a previously created memory mapping.

#include <sys/mman.h> int munmap(void *addr, size_t length);

9. Protection Flags

Flag Meaning
PROT_READ Pages may be read.
PROT_WRITE Pages may be written.
PROT_EXEC Pages may contain executable instructions.
PROT_NONE No access permitted.

10. Interview Questions

  1. What is memory mapping?
  2. What problem does mmap() solve?
  3. Which header file declares mmap()?
  4. What does munmap() do?
  5. What does PROT_READ mean?
  6. Why is MAP_FAILED used instead of NULL?
  7. What is virtual memory?
  8. Can mapped memory represent a file?
  9. When should munmap() be called?
  10. Why is memory mapping faster than repeated read() operations in many workloads?

11. Mapping Flags

Mapping flags determine how the mapped memory behaves and whether changes made through the mapping are visible to other processes or written back to the underlying file.

12. MAP_SHARED

The MAP_SHARED flag creates a shared mapping. Changes made to the mapped memory may become visible to other processes that map the same file and can be synchronized back to the underlying file.

File ↓ MAP_SHARED ↓ Process A ↔ Process B

13. MAP_PRIVATE

The MAP_PRIVATE flag creates a private mapping. Modifications made through the mapping are not visible to other processes and are not written back to the underlying file. This behavior is commonly implemented using copy-on-write (COW).

File ↓ MAP_PRIVATE ↓ Private Copy ↓ Modified Pages

14. MAP_SHARED vs MAP_PRIVATE

Feature MAP_SHARED MAP_PRIVATE
Shared Between Processes Yes No
Writes Affect File Yes (after synchronization) No
Copy-On-Write No Yes
Typical Use Inter-process sharing Private processing

15. Anonymous Mapping

Anonymous mappings are not backed by a file. Instead, the operating system provides zero-initialized memory pages that exist only for the lifetime of the mapping.

mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

16. File-Backed Mapping

A file-backed mapping associates a region of virtual memory with an existing file. Applications access file contents directly through memory instead of performing repeated read() and write() operations.

17. Practical Example

#include #include #include #include int main(void) { int fd; fd = open("sample.txt", O_RDONLY); if (fd == -1) return 1; char *data = mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, fd, 0); if (data == MAP_FAILED) return 1; printf("%.20s\n", data); munmap(data, 4096); close(fd); return 0; }

18. msync()

The msync() function synchronizes a mapped region with its underlying storage. This is primarily useful for shared writable mappings.

#include int msync(void *addr, size_t length, int flags);

19. msync() Flags

Flag Description
MS_SYNC Wait until synchronization completes.
MS_ASYNC Schedule synchronization asynchronously.
MS_INVALIDATE Invalidate cached copies where supported.

20. Interview Questions

  1. What is the purpose of MAP_SHARED?
  2. How does MAP_PRIVATE differ from MAP_SHARED?
  3. What is copy-on-write?
  4. What is an anonymous mapping?
  5. When is msync() required?
  6. Which mapping type is commonly used for shared memory?
  7. Why is MAP_FAILED checked after calling mmap()?
  8. What does MS_SYNC do?
  9. Can anonymous mappings be backed by files?
  10. Why are memory mappings often more efficient than repeated file I/O?

21. mprotect()

The mprotect() function changes the access protection of an existing memory mapping. It can modify whether mapped pages are readable, writable, executable, or inaccessible.

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

22. Example Using mprotect()

if (mprotect(addr, length, PROT_READ) == -1) { perror("mprotect"); }

The mapped pages become read-only after the protection change.

23. madvise() (Supplementary)

The madvise() function allows an application to provide the kernel with information about the expected access pattern for a mapped region. The operating system may use this information to improve memory management decisions.

#include <sys/mman.h> int madvise(void *addr, size_t length, int advice);

Note: This interface is implementation-dependent and is presented as a Linux/POSIX extension rather than a core APUE topic.

24. mlock()

The mlock() function requests that the specified memory pages remain resident in physical memory. Locking memory helps prevent paging for latency-sensitive or security-sensitive applications.

#include <sys/mman.h> int mlock(const void *addr, size_t len);

25. munlock()

The munlock() function removes a previous memory lock, allowing the operating system to page the memory if necessary.

#include <sys/mman.h> int munlock(const void *addr, size_t len);

26. Shared Memory with mmap()

Two or more related processes can communicate by mapping the same file or shared memory object using MAP_SHARED. Changes made by one process become visible to other processes mapping the same region.

Shared File ↓ MAP_SHARED ↓ Process A ↔ Shared Pages ↔ Process B

27. Linux Memory Mapping Commands

Command Purpose
pmap <pid> Display the memory map of a running process.
cat /proc/<pid>/maps Display all mapped memory regions.
cat /proc/<pid>/smaps Display detailed memory mapping statistics.
vmstat Display virtual memory statistics.

28. Best Practices

  • Unmap memory using munmap() when it is no longer required.
  • Request only the minimum required protection flags.
  • Use MAP_SHARED only when data sharing is required.
  • Always verify the return value of mmap() against MAP_FAILED.
  • Lock memory only when necessary because excessive locking reduces available physical memory.

29. Common Programming Mistakes

  • Forgetting to call munmap().
  • Checking for NULL instead of MAP_FAILED.
  • Requesting unnecessary write permissions.
  • Using MAP_PRIVATE when shared updates are required.
  • Locking excessive amounts of memory with mlock().

30. Interview Questions

  1. What is the purpose of mprotect()?
  2. Why would an application call mlock()?
  3. What does munlock() do?
  4. How does MAP_SHARED support inter-process communication?
  5. Which command displays the memory map of a process?
  6. What information is available in /proc/<pid>/maps?
  7. Why should munmap() always be called?
  8. Why is MAP_FAILED checked instead of NULL?
  9. What is the purpose of madvise()?
  10. When is memory locking useful?

31. Memory Mapping API Comparison

Function Purpose
mmap() Create a new memory mapping.
munmap() Remove an existing memory mapping.
mprotect() Modify memory protection permissions.
msync() Synchronize mapped memory with storage.
mlock() Lock mapped pages into physical memory.
munlock() Unlock previously locked pages.

32. Complete Memory Mapping Workflow

Open File ↓ File Descriptor ↓ mmap() ↓ Virtual Address Space ↓ Application Accesses Memory ↓ (Optional) mprotect() ↓ (Optional) msync() ↓ munmap() ↓ close()

33. Linux Memory Mapping Commands

Command Purpose
pmap <pid> Display memory mappings of a process.
cat /proc/<pid>/maps Display mapped address regions.
cat /proc/<pid>/smaps Display detailed mapping statistics.
vmstat Display virtual memory statistics.
free -h Display system memory usage.
cat /proc/meminfo Display kernel memory information.

34. Best Practices Review

  • Always check whether mmap() returns MAP_FAILED.
  • Call munmap() before terminating the program or when the mapping is no longer required.
  • Request only the minimum required protection flags.
  • Use MAP_SHARED only when processes must share updates.
  • Synchronize writable shared mappings when persistence is required.
  • Avoid locking excessive memory using mlock().

35. Common Programming Mistakes

  • Testing for NULL instead of MAP_FAILED.
  • Accessing memory after calling munmap().
  • Using an invalid file descriptor with mmap().
  • Ignoring page-alignment requirements for mapping offsets.
  • Forgetting to synchronize writable shared mappings when needed.
  • Requesting executable permission unnecessarily.

36. Real-World Applications

Application Usage
Database Systems Memory-mapped database files.
Web Browsers Efficient loading of large cache files.
Image Processing Direct access to large image files.
Embedded Systems Memory-mapped device registers.
Inter-Process Communication Shared memory between related processes.

37. Advanced Interview Questions

  1. How does mmap() differ from read()?
  2. Why does mmap() return MAP_FAILED instead of NULL?
  3. What is the purpose of MAP_PRIVATE?
  4. Explain copy-on-write.
  5. When should msync() be called?
  6. How does mprotect() improve security?
  7. Why is mlock() useful for cryptographic applications?
  8. How can two processes communicate using MAP_SHARED?
  9. Which Linux command displays detailed memory mapping statistics?
  10. What happens if a program accesses memory after calling munmap()?

38. Module Summary

This module introduced POSIX memory mapping interfaces for efficient file access and inter-process communication. We studied mmap(), munmap(), mprotect(), msync(), mlock(), and munlock(), along with memory protection flags, shared and private mappings, anonymous mappings, synchronization, Linux diagnostic utilities, recommended programming practices, and common pitfalls. Memory mapping is a fundamental technique used in operating systems, high-performance applications, databases, and embedded software to reduce I/O overhead and provide efficient access to large data sets.

Knowledge Check

Concept Mastery Assessment — Module 37

Verify your conceptual understanding with 12 targeted technical assessment questions. Instant feedback and explanations are provided for every choice.

Question 1 of 12
What is the primary architectural purpose of Memory Mappings, mmap & Anonymous Memory in operating systems?
Explanation
Memory Mappings, mmap & Anonymous Memory is designed to manage mmap system call, map_shared vs map_private, map_anonymous allocation, msync flush synchronization, and munmap deallocation. within the operating system architecture.
Question 2 of 12
Which system interface or data structure is centrally associated with Memory Mappings, mmap & Anonymous Memory?
Explanation
Under POSIX and Linux, Memory Mappings, mmap & Anonymous Memory operates through standardized system calls and kernel control structures.
Question 3 of 12
What safety or concurrency constraint must developers consider when implementing Memory Mappings, mmap & Anonymous Memory?
Explanation
Proper synchronization, avoidance of race conditions, and handling reentrant execution are critical when working with Memory Mappings, mmap & Anonymous Memory.
Question 4 of 12
When a system call related to Memory Mappings, mmap & Anonymous Memory fails in C, how does the POSIX runtime conventionally report the failure?
Explanation
Standard POSIX system calls return -1 or NULL on error, assigning an error integer (e.g. EINVAL, EPERM, EAGAIN) to the thread-local errno variable.
Question 5 of 12
What is the primary performance tradeoff associated with Memory Mappings, mmap & Anonymous Memory?
Explanation
Operations involving Memory Mappings, mmap & Anonymous Memory balance performance against kernel transition, memory bandwidth, and cache locality tradeoffs.
Question 6 of 12
What security principle governs access to resources in Memory Mappings, mmap & Anonymous Memory?
Explanation
The kernel validates credentials, effective permissions, and Linux capabilities before granting access to protected operations.
Question 7 of 12
How does execution of Memory Mappings, mmap & Anonymous Memory transition between User Space and Kernel Space?
Explanation
User space transitions to kernel mode securely via software traps or SYSCALL instructions that switch processor rings to Ring 0.
Question 8 of 12
What happens to resources allocated by Memory Mappings, mmap & Anonymous Memory when the owning process terminates?
Explanation
Process resources (open fds, memory maps) are automatically reclaimed by the kernel on termination, while kernel-persistent objects survive.
Question 9 of 12
In production Linux server environments, how is Memory Mappings, mmap & Anonymous Memory optimized for high throughput?
Explanation
Linux optimizes throughput via zero-copy data paths, asynchronous kernel events, and scalable concurrency primitives.
Question 10 of 12
What standard governs the portability of Memory Mappings, mmap & Anonymous Memory across Unix, Linux, and macOS platforms?
Explanation
IEEE POSIX standards define consistent APIs across Unix-like platforms ensuring portable source code execution.
Question 11 of 12
Which command-line diagnostic tool is most effective for inspecting and troubleshooting Memory Mappings, mmap & Anonymous Memory at runtime?
Explanation
Utilities like strace, lsof, and the /proc filesystem provide direct visibility into kernel interactions and resource status.
Question 12 of 12
What is a critical production best practice when developing systems software involving Memory Mappings, mmap & Anonymous Memory?
Explanation
Defensive programming requires explicit error checking on all system operations, proper resource cleanup, and avoiding memory corruption.
0 / 12 (0%)
Great job! Review the concepts above and proceed when ready.
ADVERTISEMENT
Responsive Ad Unit • Technical Courses & Certifications