Skip to content
Visual explainer 4h to learn 4 steps

POSIX shared memory & semaphores

Share a memory region between processes and synchronise access with semaphores.

By Invicly Tech, , in Linux System Programming. About 11 minutes to read.

Topic 22 of 42

In short

Shared memory lets processes map the same physical pages, so data is exchanged without copying through the kernel. It is the fastest form of IPC, but the kernel provides no synchronisation, so you add semaphores or process-shared mutexes. POSIX shared memory objects appear under /dev/shm.

Explained simply

Most ways of talking between processes copy data: the sender hands bytes to the kernel, and the kernel copies them to the receiver. Shared memory skips that. Two processes look at the very same piece of memory, so what one writes the other can read immediately.

Think of a whiteboard in a shared office. Anyone can write on it and everyone sees the change at once. That is very fast. But if two people write in the same spot at the same time, the result is a mess. So you need a rule, such as "only the person holding the marker may write".

In programs, that rule is a semaphore or a lock. A semaphore is a counter that processes decrease before entering and increase when leaving. If the counter is zero, the next process waits. The kernel does not add any such rule for you; you must add it yourself.

POSIX shared memory objects have names like /demo and live in /dev/shm, which is memory, not disk. They stay there until someone deletes them or the machine reboots, even after every program using them has exited.

Press Play on a diagram to walk through it one step at a time.

SequenceTwo processes sharing a region
Writer
Kernel
Reader
  1. 1shm_open /demo, ftruncate to 4096 bytes
    Writer to Kernel: shm_open /demo, ftruncate to 4096 bytes
  2. 2mmap MAP_SHARED
    Writer to Kernel: mmap MAP_SHARED
  3. 3shm_open /demo, mmap MAP_SHARED
    Reader to Kernel: shm_open /demo, mmap MAP_SHARED
  4. 4write into shared pages, then sem_post
    Writer to Reader: write into shared pages, then sem_post
  5. 5sem_wait returns, read the same pages directly
    Reader to Writer: sem_wait returns, read the same pages directly
  6. 6shm_unlink /demo when finished
    Writer to Kernel: shm_unlink /demo when finished
CompareWays to get shared memory
POSIX shm_open
  • Named object in /dev/shm
  • Unrelated processes can open it
  • Remove with shm_unlink
  • Modern, file-like API
MAP_SHARED | MAP_ANONYMOUS
  • No name at all
  • Created before fork
  • Only parent and children share it
  • Freed when the last user exits
memfd_create
  • Anonymous file descriptor
  • Send it over a Unix socket
  • Can be sealed read-only
  • Linux only

In depth

What shm_open and mmap really create

shm_open("/demo", O_CREAT | O_RDWR, 0600) creates a file in /dev/shm, which is a tmpfs: a file system kept in RAM. The name must start with a slash and contain no other slashes. A new object has size 0, so ftruncate sets its size; the new bytes read as zero. mmap with MAP_SHARED then maps the object's pages into your address space.

When a second process maps the same object, its page tables point at the same physical pages. No data is ever copied. The pages count as Shmem in /proc/meminfo, and /dev/shm is usually limited to half of RAM. Because each process may map the region at a different virtual address, store offsets inside the region, never raw pointers.

MapOne object, two views
Physical pages of /dev/shm/demo
  • Process A
    • Mapped at 0x7f12a000
    • Reads and writes directly
  • Process B
    • Mapped at 0x7f88c000
    • Sees A's writes at once
  • tmpfs name
    • /dev/shm/demo
    • Removed by shm_unlink

POSIX semaphores: named and unnamed

A semaphore holds a non-negative count. sem_wait decreases it, or blocks while it is zero; sem_post increases it and wakes one waiter. Start the count at 1 to use it as a lock, or at 0 to use it as a "data is ready" signal. sem_post is async-signal-safe, so even a signal handler may call it. sem_trywait never blocks, and sem_timedwait takes an absolute CLOCK_REALTIME deadline.

Named semaphores come from sem_open("/name", O_CREAT, 0600, 1) and appear as /dev/shm/sem.name, so unrelated programs can find them; remove them with sem_unlink. Unnamed semaphores are placed inside your shared region and set up with sem_init(&s, 1, 1), where the 1 in the middle means shared between processes. Unnamed ones are handy because the lock lives right next to the data it protects. Always handle EINTR from sem_wait.

  • Build with gcc -pthread
  • sem_getvalue shows the current count, useful for debugging
  • A semaphore has no owner, so any process may post it

Process-shared mutexes and crash safety

A pthread mutex can also work across processes when it lives in shared memory and its attributes say PTHREAD_PROCESS_SHARED. Condition variables have the same attribute, so you can build a full producer and consumer queue in shared memory.

The hard question is what happens when a process dies while holding the lock. With a semaphore nothing tells the others; the count just stays at zero and everyone waits forever. A robust mutex solves this: set PTHREAD_MUTEX_ROBUST with pthread_mutexattr_setrobust. If the owner dies, the next pthread_mutex_lock returns EOWNERDEAD. That process now holds the lock, should repair the data, and calls pthread_mutex_consistent before unlocking. C11 atomics on lock-free types also work across processes and are good for simple counters and flags.

Lifecycle, setup races and cleanup

Shared memory outlives processes. Unmapping or exiting does not remove the object; only shm_unlink (or rm in /dev/shm) does, and the memory is freed after the last mapping is gone, just like unlinking an open file. Forgotten objects keep using RAM until reboot.

When several processes start at once, decide who sets things up. Open with O_CREAT | O_EXCL: exactly one process succeeds and initialises the region (sizes, semaphores, a header with a magic number and version), and the others get EEXIST, open without O_CREAT and wait until the header says ready. Never shrink an object while others have it mapped: touching a page beyond the new end raises SIGBUS.

FlowSafe startup of a shared region
  1. 1
    shm_open O_CREAT|O_EXCL

    Only one process wins.

  2. 2
    Winner: ftruncate and mmap

    Zero-filled region.

  3. 3
    Winner: init header

    sem_init, version, then ready = 1.

  4. 4
    Others: open and map

    Wait until ready is set.

  5. 5
    Last user: shm_unlink

    Name removed, RAM freed after munmap.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Create shared memory with shm_open~1h
  2. 2
    Size and map it with ftruncate and mmap~1h
  3. 3
    Synchronise with POSIX semaphores~1h
  4. 4
    Clean up with shm_unlink~1h

Key points

  • shm_open returns a descriptor, ftruncate sets the size and mmap with MAP_SHARED maps it.
  • Data written by one process is immediately visible to the other.
  • Protect shared data with a semaphore or a pthread mutex marked PTHREAD_PROCESS_SHARED.
  • Store offsets rather than pointers, because each process may map the region at a different address.
  • Remove the object with shm_unlink or it lingers in /dev/shm.

Key terms

Tap a card to flip it. 0/5 known

Examples

c
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

int main(void) {
  int fd = shm_open("/demo", O_CREAT | O_RDWR, 0600);
  if (fd < 0 || ftruncate(fd, 4096) < 0) { perror("shm"); return 1; }
  char *p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  if (p == MAP_FAILED) { perror("mmap"); return 1; }
  snprintf(p, 4096, "written by pid %d", getpid());
  printf("%s (see /dev/shm/demo)\n", p);
  munmap(p, 4096); close(fd);
  return 0;
}

Create and write a shared region; link with -lrt on older glibc.

Two processes increment one counter correctly

Parent and child each add 1 to a shared counter a million times. Step 1: create an anonymous shared mapping before fork, so both see it. Step 2: put an unnamed semaphore inside it with pshared set to 1 and a starting value of 1. Step 3: each increment happens between sem_wait and sem_post. Step 4: the parent waits and prints 2000000. Remove the two semaphore calls in the loop and the total comes out lower, because updates are lost. Build with gcc -pthread.

c
#include <semaphore.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
struct shared { sem_t lock; long counter; };
int main(void) {
  struct shared *s = mmap(NULL, sizeof *s, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  if (s == MAP_FAILED || sem_init(&s->lock, 1, 1) < 0) { perror("setup"); return 1; }
  pid_t pid = fork();
  if (pid < 0) { perror("fork"); return 1; }
  for (int i = 0; i < 1000000; i++) { sem_wait(&s->lock); s->counter++; sem_post(&s->lock); }
  if (pid == 0) _exit(0);
  waitpid(pid, NULL, 0);
  printf("counter = %ld (expect 2000000)\n", s->counter);
  return 0;
}

Finding and cleaning leftover objects

After a few crashed test runs, the server is short on memory. Step 1: list /dev/shm; POSIX shared memory objects and named semaphores (sem.*) live there. Step 2: check how full the tmpfs is and how much RAM is counted as Shmem. Step 3: see whether any process still maps an object before deleting it. Step 4: remove the leftovers; rm does the same as shm_unlink or sem_unlink.

bash
ls -l /dev/shm
df -h /dev/shm
grep Shmem: /proc/meminfo
sudo lsof /dev/shm/demo        # any process still using it?
rm /dev/shm/demo /dev/shm/sem.demo_lock

Quick reference

  • shm_open, then ftruncate to set the size, then mmap with MAP_SHARED
  • Names look like /demo: one leading slash, no others
  • sem_init(&s, 1, 1) makes an unnamed semaphore shared between processes
  • Named semaphores appear in /dev/shm as sem.NAME
  • Store offsets, not pointers, in shared memory
  • Use O_CREAT | O_EXCL so exactly one process initialises the region
  • Robust mutexes return EOWNERDEAD when the previous owner died
  • Nothing is removed at exit; call shm_unlink and sem_unlink

Common mistakes

  • Skipping synchronisation and reading half-written data.
  • Forgetting shm_unlink so stale objects survive restarts.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why should a linked list in shared memory use offsets instead of pointers?

Question 2

2What does a new POSIX shared memory object contain right after shm_open with O_CREAT?

Question 3

3A process holding a semaphore-based lock crashes. What happens to the other processes?

Question 4

4Every program using /dev/shm/demo has exited. Is the memory freed?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write program A that creates /greeting, writes a message into it and exits, and program B that maps it read-only and prints the message.

  2. Exercise 2medium

    Make a one-slot mailbox in shared memory: the writer puts a string and posts a "full" semaphore; the reader waits on it, prints the string and posts an "empty" semaphore.

  3. Exercise 3hard

    Put a robust, process-shared mutex in shared memory. Have a child lock it and exit without unlocking; the parent must detect this and recover.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is shared memory the fastest IPC on Linux?
Yes for moving data, because nothing is copied. But you pay with the effort of synchronising access correctly.
Where can I see POSIX shared memory objects?
In /dev/shm. You can list them with ls -l and remove leftovers with rm.
Should I use System V shared memory (shmget) or POSIX?
Prefer POSIX shm_open for new code; its file-like API is simpler. System V shared memory still works and is listed with ipcs -m.
Do I need a lock if only one process writes?
Usually yes, or at least atomics: the reader can otherwise see a half-written record. A semaphore or a sequence counter tells it when data is complete.

Go deeper

ShareXLinkedInWhatsApp