Understanding Linux mmap: Memory Mapping, Shared Memory, and IPC Mechanisms
This article explains Linux's mmap mechanism, its relationship with shared memory, the advantages and disadvantages of mmap versus traditional shared memory, and provides practical code examples and detailed steps for using mmap in interprocess communication and large‑file handling.
Linux's mmap (memory map) is a mechanism that maps files or devices into a process's virtual address space, allowing direct memory access without traditional read/write system calls.
Shared memory can be implemented via mmap() of regular files or anonymous mappings, providing fast interprocess communication, while System V shared memory (shm) maps directly to physical memory.
Advantages of mmap include the ability to map storage larger than physical RAM; its disadvantage is slower read/write speed compared to pure RAM. shm offers faster access but is limited by physical memory size.
In practice, use shm for small shared regions and mmap for larger ones.
Two ways to use mmap for shared memory: (1) map a regular file, (2) use anonymous mapping with fork(). Example code:
fd=open(name, flag, mode);
if(fd<0)
...
ptr=mmap(NULL, len , PROT_READ|PROT_WRITE, MAP_SHARED , fd , 0);Another example shows creating a shared memory segment with shmget/shmat/shmdt/shmctl:
//建立共享内存区域
int shared_id;
char *region;
const int shm_size = 1024;
shared_id = shmget(IPC_PRIVATE,
shm_size,
IPC_CREAT | IPC_EXCL |
S_IRUSR | S_IWUSR);
region = (char*) shmat(shared_id, 0, 0);
...
shmdt(region);
shmctl(shared_id, IPC_RMID, 0);mmap creates a vm_area_struct representing a virtual memory area, linking file pages to virtual addresses. The mapping process involves three stages: (1) creating the virtual area in user space, (2) establishing kernel‑level file‑to‑address mapping, and (3) handling page‑faults to bring data into physical memory.
Compared with conventional file I/O, which copies data from disk to page cache to user space, mmap can bypass the page cache, reducing copies to a single transfer from disk directly to user space, thus improving performance, especially for large data.
Key advantages of mmap are fewer data copies, efficient user‑kernel interaction, support for interprocess communication, and the ability to handle large files without exhausting RAM.
Deepin Linux
Research areas: Windows & Linux platforms, C/C++ backend development, embedded systems and Linux kernel, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.