Shared Memory and Semaphores

Learn how shared memory enables fast data exchange, and how semaphores are used to synchronize access and prevent conflicts.

So far, we have seen IPC mechanisms in which the kernel acts as an intermediary. While convenient, this means data is copied between processes through the kernel-managed buffers. Shared memory works differently. Instead of sending data through the kernel, shared memory allows multiple processes to map the same memory region into their address spaces. Once mapped, the processes can read and write directly to that region. This makes shared memory the fastest form of interprocess communication.

However, because multiple processes access the same memory, synchronization becomes essential. Without coordination, simultaneous access can corrupt data. For that reason, shared memory is commonly used together with semaphores.

What is POSIX shared memory?

POSIX shared memory allows processes to create a memory object that behaves similarly to a file. It is identified by a name (starting with /) and accessed using system calls.

The typical sequence for using shared memory is as follows:

  1. Create or open a shared memory object using shm_open().

  2. Set its size using ftruncate().

  3. Map it into the process’s address space using mmap().

  4. Access it like a normal pointer.

  5. Unmap and remove it when finished.

Unlike pipes, once memory is mapped, no additional system calls are required to read or write data.

Creating and mapping shared memory

Let us examine a simple example where one process writes a message into shared memory and another process reads it.