On this page
Shared Memory and Semaphores
Coverage: shmget/shmat (SysV) → mmap(MAP_SHARED) → POSIX semaphore → file locking → memfd_create → Comparison and Selection Applicable to: Linux user space
Overview
Pipes and sockets transfer data via copying, whereas shared memory allows multiple processes to access the same physical memory—zero-copy. This is the highest-performance IPC method, but it requires additional synchronization mechanisms (semaphores, file locks, or lockless data structures).
mmap(MAP_SHARED): POSIX Shared Memory
// Style 1: Anonymous shared memory (shared after fork)
void *addr = ;
// After fork: parent and child processes see the same physical page (not COW!)
// Style 2: File-backed shared memory
int fd = ;
;
void *addr = ;
// Unrelated processes: open the same file → mmap → share
// All processes see the same physical page → changes are visible to each other → synchronization required!
memfd_create: Anonymous File Descriptor
int fd = ;
;
void *addr = ;
// Advantages:
// - No filesystem mount required → no need for /dev/shm
// - Can be sealed (prevent modification): fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW)
// - Can be passed to another process: sendmsg(SCM_RIGHTS) → fd passing
// systemd uses memfd for all internal IPC
SysV Shared Memory (Legacy, Not Recommended)
int shmid = ;
void *addr = ;
// ... read/write ...
;
;
// Why it is obsolete: global key conflicts, risk of resource leaks, lack of flexibility
POSIX Semaphores
// Anonymous semaphore (for threads or shared memory):
sem_t sem;
; // pshared=1 → in shared memory
; // P (decrement by 1, block)
; // V (increment by 1, possibly wake waiters)
;
// Named semaphore (for unrelated processes):
sem_t *sem = ;
;
;
;
;
Inside sem_wait: futex
// glibc sem_wait implementation (simplified):
// Same as pthread_mutex: zero syscalls when uncontended → the power of futex
File Locking: Inter-process Mutual Exclusion
// fcntl record lock: lock a region of a file
struct flock fl = ;
; // Block and wait
// Advantages: Kernel manages automatically → process crash → lock automatically released
// Suitable for: Daemon single-instance, database file protection
Selection Guide
Scenario Recommended Solution
─────────────────────────────────────────────
Parent-child unidirectional data pipe
Parent-child bidirectional data socketpair
Unrelated processes sharing large data mmap(MAP_SHARED) + POSIX sem
Daemon single-instance + inter-process lock file lock (F_SETLK)
Thread synchronization (same process) pthread_mutex (futex)
Counting semaphore between threads/ POSIX sem (futex)
reliable credential passing AF_UNIX + SCM_CREDENTIALS
References
- man: mmap(2), shm_overview(7), sem_overview(7), fcntl(2) (record locks), memfd_create(2)
- Source code:
ipc/sem.c(SysV),ipc/shm.c,mm/mmap.c - LWN: "memfd_create and sealing"
Keywords: mmap MAP_SHARED, memfd_create, POSIX semaphore, sem_wait, futex, file lock, F_SETLK, shared memory