Skip to content

37. IPC — Shared Memory

The fastest IPC — two or more processes map the same physical memory region into their own virtual address spaces, so there's no copying and no syscalls after setup (compare: a pipe copies data twice, kernel buffer in, kernel buffer out).

POSIX flow: shm_open()ftruncate() to size it → mmap() with MAP_SHARED → use the pointer like normal memory → munmap()/shm_unlink() when done.

The big catch — no built-in synchronization. Raw memory access means simultaneous writes from two processes race and corrupt data. You must add your own mutex or semaphore, e.g. the classic producer-consumer pattern with empty_slots/filled_slots semaphores plus a mutex around the buffer access.

Real-world use: database buffer pools (PostgreSQL), web-server worker counters (Nginx), CPU↔GPU shared framebuffers, Android's Ashmem/ION for zero-copy camera frames.

Analogy: a pipe is passing notes through a middleman; shared memory is a shared whiteboard everyone can write on directly — much faster, but you need a "raise your hand before writing" rule (a mutex).