Skip to content

POSIX Shared Memory

POSIX shared memory provides a named memory object that can be mapped into multiple processes.

Unlike message-based IPC, shared memory allows processes to access the same memory region directly. This can be very efficient, but it requires explicit synchronization.

What Problem It Solves

Use POSIX shared memory when multiple processes need to exchange larger or frequently updated data with low overhead.

Typical use cases:

  • shared ring buffers
  • producer/consumer pipelines
  • high-throughput local IPC
  • shared state between cooperating processes

Core Concepts

Concept Description
shm_open() Creates or opens a POSIX shared memory object
ftruncate() Sets the size of the shared memory object
mmap() Maps the object into the process address space
munmap() Unmaps the memory region
shm_unlink() Removes the named shared memory object

Basic Flow

shm_open()
ftruncate()
mmap()
read/write shared memory
munmap() / close() / shm_unlink()

Synchronization Requirement

Shared memory only shares bytes. It does not provide locking, notification, or ordering by itself.

Use one of the following with shared memory:

  • process-shared pthread mutex
  • POSIX semaphore
  • eventfd
  • futex-based synchronization

Common Pitfalls

Warning

Do not assume shared memory access is automatically safe. Concurrent readers and writers still need synchronization.

Note

shm_unlink() removes the name, but existing mappings remain valid until unmapped and closed.