The Complete Guide to Shared Memory, Semaphores and Message Queues
A guide to shared memory, semaphores and message queues on Linux: POSIX and System V APIs, layout, locking, robust mutexes, crash recovery, limits and cleanup.

Shared memory is the fastest way for two processes to share data, and the way that leaves the most to you. The kernel maps the same pages into both address spaces and then steps out of the way: no copy, no system call per access, and no help. It does not tell you when the other side has written, it does not stop two writers from colliding and it does not notice when one of them dies in the middle of an update. Semaphores and message queues are the kernel's answer to those gaps, and together the three form the toolkit for local inter-process communication that outlives any one process. This guide covers all three on Linux 6.12 with glibc 2.41, in both the POSIX and the System V APIs: how to lay out shared data, how to protect it, how to survive a crashed peer, how to size and secure it and how to clean up, with complete C samples and their output.
The reference material is the Linux man pages shm_overview(7), sem_overview(7), mq_overview(7) and svipc(7), and the POSIX specification of shm_open.
Shared memory removes the kernel from the data path and leaves you with three jobs the kernel used to do: deciding who may touch a byte, noticing that the writer has finished and cleaning up when someone crashes. Pick the tools for those three jobs before you write the first line.
The three objects and the two APIs
Each of the three objects has a POSIX and a System V version. They do the same work with different interfaces, and a program can mix them, though that doubles the cleanup.
| Object | What it is | POSIX API | System V API |
|---|---|---|---|
| Shared memory | Pages mapped into several processes | shm_open(), ftruncate(), mmap() | shmget(), shmat() |
| Semaphore | A counter that processes wait on and signal | sem_open(), sem_init(), sem_wait(), sem_post() | semget(), semop() |
| Message queue | An ordered store of discrete messages | mq_open(), mq_send(), mq_receive() | msgget(), msgsnd(), msgrcv() |
POSIX objects have names such as /jobs, and on Linux they show up as files under /dev/shm and /dev/mqueue. System V objects have numeric keys, usually made with ftok(), and are listed by ipcs. POSIX IPC vs System V IPC compares the two in detail, and the short version is: use POSIX for new Linux code, and System V when you need SEM_UNDO, atomic operations on several semaphores or compatibility with existing software.
Two facts hold for all six. First, the objects outlive the processes that use them. A pipe disappears with its last descriptor, but a shared memory segment, a semaphore or a queue stays in the kernel until someone removes it or the machine reboots. That is useful for state that survives restarts and a steady source of leaks. Second, none of them crosses a machine boundary. For that you need a network protocol.
Shared memory between related processes
When the processes share an ancestor, the simplest shared memory needs no name at all. Map an anonymous shared region before fork(), and every child sees the same pages.
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
char *region = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
pid_t pid;
if (region == MAP_FAILED) {
perror("mmap");
return 1;
}
pid = fork();
if (pid == 0) {
strcpy(region, "written by the child");
_exit(0);
}
waitpid(pid, NULL, 0);
printf("parent sees: %s\n", region);
munmap(region, 4096);
return 0;
}parent sees: written by the childMAP_SHARED is the part that matters. With MAP_PRIVATE, the child would write to a private copy and the parent would see an empty string. Nothing is left behind: the region disappears when both processes have unmapped it or exited, so there is no cleanup to forget. This is the best design for a parent and its workers, and you should prefer it to any named object when it fits.
Shared memory between unrelated processes
Strangers need a name. POSIX shared memory is a file-like object: create it, size it, map it.
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int main(void)
{
int fd = shm_open("/guide_demo", O_CREAT | O_EXCL | O_RDWR, 0600);
char *p;
if (fd == -1) {
perror("shm_open");
return 1;
}
if (ftruncate(fd, 4096) == -1) {
perror("ftruncate");
return 1;
}
p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
strcpy(p, "hello from the creator");
printf("created /guide_demo, wrote %zu bytes\n", strlen(p));
return 0;
}created /guide_demo, wrote 22 bytesA second program opens the same name with shm_open("/guide_demo", O_RDWR, 0), maps it and reads the text. The object lives at /dev/shm/guide_demo and stays after the creator exits, until shm_unlink("/guide_demo") or rm removes it. O_EXCL makes creation fail with EEXIST if a stale object is there, which is how you tell "I am the creator" from "someone else got here first". Share memory between processes with shm_open and mmap builds a full writer and reader with a handshake and covers the common mistakes: forgetting ftruncate(), mapping with MAP_PRIVATE and sharing pointers.
The System V route does the same job through shmget() and shmat(), with the extra option of IPC_RMID right after attaching, so a segment shared across fork() frees itself when the last process exits. Use System V shared memory with shmget and shmat covers keys, identifiers and the errors.
Designing the shared layout
The memory is raw bytes, and both sides must agree on what they mean, forever. These rules prevent most layout bugs.
No pointers. A pointer is an address in one process, and the region may map at a different address in the next. Store offsets from the start of the region, or indexes into an array in it.
Fixed-width types. Use uint32_t, int64_t and char[N], never long or size_t, whose sizes differ between a 32-bit and a 64-bit build of the same program. Put the largest members first, or order them so that padding is the same on every compiler you use, and pin the size so a change fails the build.
A header with a magic number, a version and a size. The first fields identify the layout. A process that attaches checks them and refuses to proceed on a mismatch, which turns a silent corruption after an upgrade into a clear error message.
Cache-line separation for independent hot fields. Two counters that different processes update, if they share a 64-byte cache line, make the line bounce between cores on every update. Pad each to its own line.
#include <stdalign.h>
#include <stdatomic.h>
#include <stdint.h>
#define SHM_MAGIC 0x47554944u /* "GUID" */
#define SHM_VERSION 3u
#define NSLOTS 8
struct slot {
alignas(64) _Atomic uint64_t count; /* one cache line per writer */
};
struct shared {
uint32_t magic;
uint32_t version;
uint32_t total_size;
uint32_t nslots;
struct slot slots[NSLOTS];
};
_Static_assert(sizeof(struct slot) == 64, "slot must fill one cache line");
_Static_assert(sizeof(struct shared) == 64 + 8 * 64, "layout changed: bump SHM_VERSION");The first four fields occupy 16 bytes, and because struct slot is aligned to 64, the compiler pads the header to 64 bytes before the first slot. So struct shared is 64 plus eight slots of 64, which is 576 bytes, and the second assertion records that. A developer who adds a field sees the build fail and remembers to change the version.
An attaching process should verify the object before trusting it:
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "layout.h"
struct shared *attach_checked(const char *name)
{
struct stat st;
struct shared *s;
int fd = shm_open(name, O_RDWR, 0);
if (fd == -1)
return NULL;
if (fstat(fd, &st) == -1 || (size_t)st.st_size < sizeof *s) {
close(fd); /* too small: never mapped */
return NULL;
}
s = mmap(NULL, sizeof *s, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
if (s == MAP_FAILED)
return NULL;
if (s->magic != SHM_MAGIC || s->version != SHM_VERSION) {
munmap(s, sizeof *s);
return NULL;
}
return s;
}The fstat() check matters. Mapping a file and touching pages beyond its end raises SIGBUS, so the size check turns that into an error return. The size check also catches the case where the creator has made the object but not yet called ftruncate().
The lost update
Two processes that each add one to a shared counter can lose an update. Each does a read, an increment in a register and a write. If both read the value 7 before either writes, both write 8 and one increment vanishes. The loss is rare for a single increment and certain over millions, and the symptom is a final count lower than the number of operations, by a different amount every run. A stress test with several processes and many increments exposes it quickly, which is the reason to write such a test rather than reason about it.
The cure is either to make the operation atomic or to serialize it with a lock. Atomic read-modify-write instructions, reached through C11 <stdatomic.h>, work in shared memory as they do between threads, provided the type is lock-free, which atomic_is_lock_free() confirms. For anything larger than one machine word, a lock is needed.
Semaphores as locks and signals
A semaphore is a counter. sem_wait() takes one from it and blocks at zero, and sem_post() adds one and wakes a waiter. Initial value 1 gives a lock, 0 gives a signal that something is ready and N gives a pool of N identical resources. For processes sharing a mapping, an unnamed semaphore placed in the shared region and initialized with sem_init(&sem, 1, value) needs no name. The nonzero second argument asks for cross-process use, and the semaphore must be in memory the processes really share.
#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);
sem_init(&s->lock, 1, 1);
s->counter = 0;
for (int w = 0; w < 2; w++) {
if (fork() == 0) {
for (int i = 0; i < 1000; i++) {
sem_wait(&s->lock);
s->counter++;
sem_post(&s->lock);
}
_exit(0);
}
}
while (wait(NULL) > 0)
;
printf("counter = %ld\n", s->counter);
sem_destroy(&s->lock);
return 0;
}counter = 2000Use unnamed semaphores in shared memory with sem_init extends this to a bounded buffer, and synchronize processes with named POSIX semaphores covers the named kind for processes with no common ancestor, including sem_timedwait() with its absolute deadline.
One property of POSIX semaphores deserves a warning here, and the section on failures below returns to it: a process that dies between sem_wait() and sem_post() leaves the count lowered for good.
Mutexes and condition variables that cross processes
The pthread mutex can also be shared between processes, with the attribute PTHREAD_PROCESS_SHARED, if it is placed in shared memory. The advantage over a semaphore is the robust attribute: if the owner dies while holding the lock, the next process to lock it receives EOWNERDEAD instead of blocking for ever, and it can repair the data and mark the mutex consistent.
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
struct shared {
pthread_mutex_t lock;
int value;
};
int main(void)
{
struct shared *s = mmap(NULL, sizeof *s, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
pthread_mutexattr_t attr;
pid_t pid;
int rc;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
pthread_mutex_init(&s->lock, &attr);
pthread_mutexattr_destroy(&attr);
s->value = 0;
pid = fork();
if (pid == 0) {
pthread_mutex_lock(&s->lock);
s->value = 41; /* half-finished update */
_exit(0); /* dies while holding the lock */
}
waitpid(pid, NULL, 0);
rc = pthread_mutex_lock(&s->lock);
if (rc == EOWNERDEAD) {
printf("previous owner died, value was %d\n", s->value);
s->value = 0; /* repair the data */
pthread_mutex_consistent(&s->lock); /* tell the kernel it is usable again */
} else if (rc != 0) {
printf("lock failed: %s\n", strerror(rc));
return 1;
}
printf("recovered, value is %d\n", s->value);
pthread_mutex_unlock(&s->lock);
pthread_mutex_destroy(&s->lock);
return 0;
}previous owner died, value was 41
recovered, value is 0If the new owner unlocks without calling pthread_mutex_consistent(), the mutex becomes permanently unusable and later locks fail with ENOTRECOVERABLE. Robust mutexes are the POSIX answer to the crash problem that System V solves with SEM_UNDO, and they give the next locker the chance to see that the data may be half written.
Avoiding the lock: one writer per slot
The best lock is the one you do not need. If each process writes only its own field and others only read it, there is nothing to serialize. A statistics table, a heartbeat array and a set of per-worker counters all fit this shape. Give each writer a cache line of its own and use atomic operations so a reader never sees a torn value.
#include <stdalign.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
#define WORKERS 4
#define INCREMENTS 100000
struct slot {
alignas(64) _Atomic uint64_t count;
};
int main(void)
{
struct slot *slots = mmap(NULL, sizeof(struct slot) * WORKERS,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
uint64_t total = 0;
for (int w = 0; w < WORKERS; w++) {
if (fork() == 0) {
for (int i = 0; i < INCREMENTS; i++)
atomic_fetch_add_explicit(&slots[w].count, 1, memory_order_relaxed);
_exit(0);
}
}
while (wait(NULL) > 0)
;
for (int w = 0; w < WORKERS; w++) {
uint64_t c = atomic_load(&slots[w].count);
printf("worker %d: %llu\n", w, (unsigned long long)c);
total += c;
}
printf("total %llu\n", (unsigned long long)total);
return 0;
}worker 0: 100000
worker 1: 100000
worker 2: 100000
worker 3: 100000
total 400000The relaxed memory order is enough because nothing else depends on the order of these increments, and the wait() calls give the parent the happens-before it needs. A monitor that reads the counters while workers run sees values that are each correct at some moment, though not a consistent snapshot of all four, which is acceptable for statistics and wrong for anything that must add up exactly at one instant. The 64-byte alignment keeps each counter on its own cache line, so the workers do not fight over a line. That figure is the common line size on x86-64 and many Arm cores, and getconf LEVEL1_DCACHE_LINESIZE reports the one on your machine.
The atomic type works across processes as long as it is lock-free. A non-lock-free atomic may be implemented with a hidden lock that lives in each process's private memory, so it would not synchronize at all. atomic_is_lock_free() tells you, and on x86-64 a 64-bit integer qualifies.
Message queues: when the data is a stream of jobs
Shared memory shares state. When the thing to pass is a sequence of separate items, jobs, requests or events, a message queue stores them for you, keeps their boundaries and blocks a sender when the queue is full. A POSIX queue also orders by priority and, on Linux, is a file descriptor you can wait on with poll().
This program starts a worker process that squares numbers sent to it through a queue. A message with a negative id tells the worker to stop.
#include <fcntl.h>
#include <mqueue.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
struct job {
int id;
int value;
};
int main(void)
{
struct mq_attr attr = { .mq_maxmsg = 8, .mq_msgsize = sizeof(struct job) };
mqd_t q;
pid_t pid;
mq_unlink("/guide_jobs");
q = mq_open("/guide_jobs", O_CREAT | O_EXCL | O_RDWR, 0600, &attr);
if (q == (mqd_t)-1) {
perror("mq_open");
return 1;
}
pid = fork();
if (pid == 0) {
struct job j;
for (;;) {
if (mq_receive(q, (char *)&j, sizeof j, NULL) == -1)
_exit(1);
if (j.id < 0)
break;
printf("job %d: %d squared is %d\n", j.id, j.value, j.value * j.value);
fflush(stdout);
}
_exit(0);
}
for (int i = 1; i <= 5; i++) {
struct job j = { .id = i, .value = 10 + i };
mq_send(q, (const char *)&j, sizeof j, 0);
}
{
struct job stop = { .id = -1, .value = 0 };
mq_send(q, (const char *)&stop, sizeof stop, 0);
}
waitpid(pid, NULL, 0);
mq_close(q);
mq_unlink("/guide_jobs");
return 0;
}job 1: 11 squared is 121
job 2: 12 squared is 144
job 3: 13 squared is 169
job 4: 14 squared is 196
job 5: 15 squared is 225The receive buffer is exactly mq_msgsize, the size of the structure, which is the size mq_receive() insists on at minimum. The queue was opened before fork(), and the child inherited the descriptor. Messages are fixed-size binary structures here, which is safe between processes of one program and risky across versions, since the layout rules above apply to messages too. Send messages between processes with POSIX mq_send and mq_receive covers priorities, the EMSGSIZE trap, the limits under /proc/sys/fs/mqueue and queue state in /dev/mqueue.
The System V queue has a different selection scheme. Each message has a positive long type and receivers choose by type, which lets one queue carry requests and per-client replies, and msgrcv() with a negative type gives a priority queue. It cannot be waited on with poll(). Use System V message queues with msgsnd and msgrcv has the details and the byte limits that make a default queue fill after two large messages.
A queue and shared memory are often used together: pass a small message that names a slot in shared memory, so the queue carries the notification and the ordering, and the memory carries the bulk. That avoids the 8 KiB default message size and keeps the copy out of the kernel.
System V versions of the same tools
Everything above has a System V equivalent, and the semaphore side is where it differs most. A System V semaphore is a set of counters changed by semop(), which applies an array of operations atomically, so a process can take two resources at once without deadlock risk. The SEM_UNDO flag makes the kernel reverse a process's changes when it exits, so a crash cannot leave a lock held.
struct sembuf lock = { .sem_num = 0, .sem_op = -1, .sem_flg = SEM_UNDO };
struct sembuf unlock = { .sem_num = 0, .sem_op = +1, .sem_flg = SEM_UNDO };
semop(sem_id, &lock, 1); /* released automatically if we die in here */
/* critical section */
semop(sem_id, &unlock, 1);The cost is a clumsier API: you define union semun yourself, creation and initialization are two calls with a race between them, and there is no descriptor to poll. Use System V semaphores with semop and SEM_UNDO shows a gate counter that closes the race and a demonstration of the undo.
Surviving a crash
Every mechanism above is a place where a process can die at the worst moment. The three crash hazards and the tools that cover them:
| Hazard | POSIX semaphore | Robust mutex | System V semaphore with SEM_UNDO |
|---|---|---|---|
| Holder dies in the critical section | Count stays lowered, waiters block for ever | Next locker gets EOWNERDEAD | Kernel restores the count at exit |
| Data left half written | Not detected | Reported, so you can repair | Not detected, the lock is just released |
| Waiter dies | No effect | No effect | Its undo is applied |
None of them repairs the data. They release the lock or report the death, and what to do with a half-written structure is your design. The usual tools are a sequence number written before and after an update (an odd value means an update was in progress), a dirty flag set before and cleared after and a checksum over the structure. A reader that finds the inconsistent state either rebuilds from the source of truth or discards the record.
For death of the peer rather than a lock holder, shared memory gives no signal at all, unlike a pipe, which reports it as end-of-file. Add a heartbeat: each process stores a timestamp from CLOCK_MONOTONIC in its own slot at a fixed interval, and a monitor treats a slot older than a few intervals as dead. Because the timestamp is written with an atomic store into its own cache line, the heartbeat costs almost nothing. The supervisor can also hold a pidfd for each worker, as in get notified when a child exits with pidfd_open and poll, which reports the exit at once for children it started.
Plan the start-up crash path as well. A previous run may have left a segment, a semaphore or a queue behind, with an old layout or a stuck count. Remove or reinitialize at start: shm_unlink(), sem_unlink() and mq_unlink() before creating with O_EXCL, and never trust an existing object's contents without checking its magic number and version.
Cleaning up what outlives you
Because the objects persist, ownership of cleanup must be decided at design time. Three patterns work:
Unlink early. After every peer has opened the object, unlink the name. The memory stays alive for those who hold it and is freed when the last one exits. For System V, call
IPC_RMIDright after attaching. This pattern leaks nothing even on a crash.A supervisor owns the lifetime. One process creates the objects, starts the workers, and removes the objects when it exits, with a handler for
SIGTERMthat sets a flag and the cleanup in the main flow, as in write async-signal-safe signal handlers.A sweep at start. Remove stale objects with your name before creating new ones.
For inspection and emergency cleanup, use the shell. POSIX objects are files, so ls /dev/shm /dev/mqueue lists them and rm removes them. System V objects show up in ipcs, and ipcrm removes them. List and remove stale IPC objects with ipcs and ipcrm explains the columns, how to tell an orphan from a live segment by nattch and creator PID, and a careful script for removing your own unattached segments.
Limits you will meet
| Limit | Where | Typical symptom |
|---|---|---|
Size of /dev/shm | df -h /dev/shm, half of RAM by default, 64 MiB in many container runtimes | SIGBUS when touching a page beyond what the filesystem can back |
| Queue length and message size | /proc/sys/fs/mqueue/msg_max, msgsize_max, queues_max | EINVAL from mq_open() with large attributes |
| Per-user queue memory | RLIMIT_MSGQUEUE, 819,200 bytes by default | EMFILE from mq_open() |
| System V segments | kernel.shmmni (4,096), shmall, shmmax | ENOSPC or ENOMEM from shmget() |
| System V queues | kernel.msgmax, msgmnb, msgmni | msgsnd() blocks on a full queue at 16,384 bytes by default |
| System V semaphores | /proc/sys/kernel/sem | ENOSPC from semget() |
| Open descriptors | ulimit -n | EMFILE from shm_open() and mq_open() |
Pages in shared memory are allocated on first touch. A large ftruncate() costs nothing until you write, which is convenient and makes failures late: the program runs, then gets SIGBUS when the filesystem cannot back the page. For a region that must not fail later, touch every page at start, or use fallocate() on the descriptor to reserve the space and fail early with ENOSPC.
Containers change the picture. Each container normally gets its own IPC namespace, which isolates System V objects and POSIX queues, so two containers cannot see each other's. POSIX shared memory and named semaphores live in /dev/shm, which is a mount, so they are shared only if the containers share that mount. Sharing IPC between containers on purpose means joining the IPC namespace of another with the runtime's option for it, and sharing /dev/shm as a volume.
Security
The objects have owners and permission bits like files, and the same mistakes apply. A mode of 0666 lets any local user read and write the region. A predictable name lets another user create the object first, with permissive modes, and read what you put in it, so create with O_EXCL or IPC_EXCL and check ownership with fstat() after opening. Use the umask and an explicit mode of 0600 or 0660, and place objects under a name that includes a purpose, not a bare /data.
Treat the contents as untrusted input whenever a less privileged process can write the region. The classic bug is a time-of-check to time-of-use race: you validate a length field and then use it, and the peer changes it in between. Copy the field into a local variable once, validate the copy and use only the copy. Never follow an offset or index read from shared memory without bounds-checking it against your own mapping size.
Publishing data safely
The most common shared-memory pattern is a one-time publish: one process fills a structure, and another reads it. The fields must be visible to the reader before the flag that says they are ready. On modern CPUs and compilers, plain stores can be reordered, so a flag set with an ordinary assignment can become visible before the data it guards. volatile does not fix this, because it controls only what the compiler emits, not the order the hardware commits the stores.
The fix is a release store on the flag and an acquire load in the reader, which C11 provides.
#include <stdatomic.h>
#include <stdint.h>
struct message {
_Atomic uint32_t ready; /* 0 = empty, 1 = filled */
uint32_t length;
char text[120];
};
void publish(struct message *m, const char *src, uint32_t n)
{
for (uint32_t i = 0; i < n; i++)
m->text[i] = src[i];
m->length = n;
atomic_store_explicit(&m->ready, 1, memory_order_release); /* data first, flag last */
}
int try_read(struct message *m, char *dst)
{
if (atomic_load_explicit(&m->ready, memory_order_acquire) == 0)
return -1; /* not published yet */
for (uint32_t i = 0; i < m->length; i++)
dst[i] = m->text[i];
return (int)m->length;
}The release store guarantees that every write before it is visible to a reader that observes the new flag value with an acquire load. This is the same rule threads follow, and it applies to processes because they share the same physical memory and the same cache-coherence hardware. Semaphores and mutexes provide the same ordering as part of their operations, so code that uses them for hand-off needs no explicit atomics for the data they protect.
A flag that is polled in a loop burns a core while it waits. For anything but the shortest waits, use a semaphore or a futex-backed primitive to sleep, and post it after the release store. That combination gives you the sleep and the ordering together.
How a reader learns that data is ready
Shared memory has no notification of its own, so the design must choose one. The options and their costs:
| Method | Reader behavior | Cost | Fits when |
|---|---|---|---|
| Spin on a flag | Busy loop reading the flag | Occupies a core, lowest latency | Dedicated cores, microsecond latency |
| Sleep and poll | Check the flag every few milliseconds | Wake-up delay up to the interval | Slow, relaxed data such as status |
| Semaphore post and wait | Sleeps in the kernel until posted | One system call when it must sleep or wake | General producer and consumer |
| Condition variable in shared memory | Sleeps on a process-shared condition | Same, with a mutex-protected predicate | Waiting on a compound condition |
Pipe or eventfd alongside | Wakes through poll() | A descriptor to pass and a write per signal | The reader already runs an event loop |
| Message queue carrying the notice | Receives a small message naming the slot | Queue limits | Many producers, decoupled in time |
The event-loop case is common enough to call out. A reader that waits on sockets with epoll cannot also block in sem_wait(). Give it an eventfd or a pipe that the writer pokes after publishing, add that descriptor to the epoll set, and the reader wakes through the loop it already has. The descriptor reaches the other process by inheritance or with SCM_RIGHTS over a Unix socket.
Condition variables across processes
When the reader waits for a condition more complex than "one more item", such as "the buffer has at least ten records or the writer has closed", a condition variable with the mutex that guards the state is the right tool. Both are initialized with the process-shared attribute and live in the shared region.
#include <pthread.h>
struct queue {
pthread_mutex_t lock;
pthread_cond_t changed;
int count;
int closed;
};
void queue_init(struct queue *q)
{
pthread_mutexattr_t ma;
pthread_condattr_t ca;
pthread_mutexattr_init(&ma);
pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED);
pthread_mutexattr_setrobust(&ma, PTHREAD_MUTEX_ROBUST);
pthread_mutex_init(&q->lock, &ma);
pthread_condattr_init(&ca);
pthread_condattr_setpshared(&ca, PTHREAD_PROCESS_SHARED);
pthread_cond_init(&q->changed, &ca);
pthread_mutexattr_destroy(&ma);
pthread_condattr_destroy(&ca);
q->count = 0;
q->closed = 0;
}
int wait_for_ten(struct queue *q)
{
int got;
pthread_mutex_lock(&q->lock);
while (q->count < 10 && !q->closed) /* always re-test in a loop */
pthread_cond_wait(&q->changed, &q->lock);
got = q->count;
pthread_mutex_unlock(&q->lock);
return got;
}The while loop is mandatory. A condition variable can wake without the condition being true, and the state may change between the wake-up and the moment the mutex is reacquired. A waiter that uses if instead acts on a stale predicate. The writer changes count under the lock and calls pthread_cond_signal() or pthread_cond_broadcast() afterwards.
A subtlety specific to processes: if the mutex is robust and the holder dies, pthread_cond_wait() returns EOWNERDEAD when it reacquires the mutex, and the caller must handle it as in the earlier robust-mutex sample. Ignoring the return value of pthread_cond_wait() in a robust design is a bug.
Evolving the layout
A deployed layout cannot change in place while old processes run. The magic and version fields let a new program recognize an old region, and there are three honest responses. Refuse: the new program exits with a clear message and the operator restarts the whole group. Migrate: a new program creates a new object with a new name, such as a version suffix in /state_v4, copies from the old, and the old name is unlinked when no one uses it. Extend compatibly: reserve fields in the first version, a block of zeros that a later version assigns meaning to, and keep each field's offset and size fixed for ever.
The second approach is the safest, because it never shares an object between two layouts, and the cost of a copy at restart is small compared with the cost of one corrupted field. Never reinterpret an existing field, and never reuse a version number for a different layout. The static assertion on the structure size, shown earlier, makes the layout change a compile error that points a developer at the version constant.
Testing shared-memory code
Races in shared memory appear under load, vanish under a debugger and leave no log. Ordinary race detectors are of limited use, because the thread sanitizer understands threads of one process and not separate processes mapping one region. The reliable methods are crude and effective:
A stress test with many processes and many iterations, with an invariant you can check at the end, such as "the counter equals the number of operations". Run it on a machine with several cores, since a single core hides lost updates.
Fault injection: kill a worker with
SIGKILLat random moments, restart it and check that the system recovers and the invariants hold. This is the only way to test the crash paths for robust mutexes, undo records and heartbeats.Invariants checked in the code at attach time and at intervals: magic and version, sequence numbers consistent, indexes within bounds. A corrupted region should fail loudly at the first check instead of misbehaving silently.
Slow-peer and fast-peer tests, adding a sleep in one side, to expose full-buffer and empty-buffer logic.
Restart tests: stop and start each side while the other keeps running.
Write these before relying on the design. A shared-memory protocol that has never survived a kill -9 has not been tested.
Sizing the region and the queue
Choose sizes from the workload, then leave room. For a shared table, the size is the header plus the entry count times the entry size, rounded up to a whole number of pages, which is 4,096 bytes on x86-64 and may be 16,384 or 65,536 on some Arm systems, so read it at run time with sysconf(_SC_PAGESIZE) instead of writing a constant. For a ring buffer, pick a power of two for the capacity, so the index wraps with a mask instead of a division, and make it large enough that a short stall in the consumer does not stall the producer, since the ring is the only thing absorbing the difference in their speeds.
For a message queue, mq_maxmsg sets how many messages may wait and mq_msgsize the largest message. A queue that is too short makes the producer block at the first burst. One that is too long hides a slow consumer until memory use is large and latency is high. A bounded queue is a feature: it turns overload into back-pressure at the producer, where you can decide to drop, wait or fail. Pick the bound deliberately, log when a send blocks or fails with EAGAIN and keep the maximum message size small enough to fit comfortably under msgsize_max, sending references to bulk data in shared memory instead of the data itself.
What the memory costs
Shared memory removes the copies and the system calls from the data path, and the costs move to places you cannot see in the source. A write from one core must travel to the other through the cache-coherence protocol, so two processes hammering the same cache line pay for the transfers, which is why separate slots get separate lines. A semaphore or futex costs a system call only when a process has to sleep or wake another, and a lock that is uncontended stays in user space. A lock that is contended turns every operation into a sleep and a wake-up, and then a message queue or a pipe, which does the same sleeping in the kernel and brings flow control with it, is no slower and far simpler.
Huge pages reduce translation overhead for large regions, through MAP_HUGETLB or a hugetlbfs mount, at the price of reserving them in advance. On machines with several memory nodes, the first process to touch a page decides where it lives, and a region whose users run on another node pays remote-access latency. None of this can be judged from first principles, so measure with your real sizes and core placement, with perf stat for context switches and cache misses, before you adopt a design for speed. Pipes vs Unix sockets vs shared memory gives a benchmark program and a method.
Inspecting the live system
Linux shows what the processes are sharing, without extra tools.
ls -l /dev/shm
grep guide_demo /proc/self/mapstotal 4
-rw------- 1 user user 4096 Nov 23 11:20 guide_demo
7f3a4c2b1000-7f3a4c2b2000 rw-s 00000000 00:26 11230 /dev/shm/guide_demoThe s in rw-s marks a shared mapping, where a private one shows p, and the path names the object. A mapping whose object was unlinked while mapped shows (deleted) after the path. lsof /dev/shm/guide_demo lists every process that has the object mapped or open, and ipcs -m -p shows the creator and last-operator PIDs of System V segments. For a process that is stuck, strace -f -p PID shows futex(...) calls for semaphores and mutexes, mq_timedreceive for queues and semop for System V semaphores, which tells you which primitive it is waiting on.
When a counter or a layout looks wrong, dump the region bytes directly: for POSIX shared memory xxd /dev/shm/guide_demo | head, since the object is a file. That is the fastest way to confirm that two programs agree about offsets.
Choosing the mechanism
| Need | Use |
|---|---|
| A parent and its workers share a table | Anonymous MAP_SHARED memory, atomics per slot |
| Unrelated processes share a large buffer | POSIX shared memory plus a semaphore or a robust mutex |
| Jobs or requests flow from producers to consumers | A POSIX message queue |
| One queue carries requests and replies by recipient | A System V message queue with types |
| A crashed holder must never freeze the others | A robust mutex, or a System V semaphore with SEM_UNDO |
| Two resources must be taken together | A System V semaphore set |
| Streaming bytes between related processes | A pipe, which is simpler, as in the complete guide to pipes and FIFOs |
| Many clients with separate conversations | A Unix domain socket |
IPC mechanisms compared places these next to pipes, sockets and signals, and POSIX IPC vs System V IPC settles the API question. Start from the simplest thing that works: a pipe or socket if you can afford the copies, shared memory only where the data is large or the access pattern is a shared table.
When not to use any of this
If the two parties are threads of one process, ordinary memory with a mutex or a lock-free queue does the job and needs no cleanup. If they are on different machines, you are designing a protocol. And if the data must survive a reboot, shared memory and queues will not: they live in RAM and vanish when the machine restarts, so write to a file or a database. Shared memory is also a poor fit for a team that cannot afford the debugging cost of races, since the failures appear only under load and leave no log; a socket-based design with a clear protocol is easier to test and to observe.


