Use Unnamed Semaphores in Shared Memory with sem_init
Use unnamed POSIX semaphores in a shared mapping with sem_init and pshared set to 1 to build a bounded producer and consumer buffer between forked processes.

A named semaphore needs a name, a cleanup and a trip through /dev/shm. When the processes already share memory, because one process forked after mapping it, an unnamed semaphore placed inside that memory is simpler: no name to choose, no sem_unlink() to forget and no collision with a leftover from a crash. This post builds a bounded buffer between a producer and a consumer with three such semaphores, on Linux 6.12 with glibc 2.41, following sem_init(3) and sem_overview(7).
The named variant is in synchronize processes with named POSIX semaphores. This post assumes you know the basics of sem_wait() and sem_post(), and it also touches the memory-sharing idea from share memory between processes with shm_open and mmap, applied with an anonymous mapping.
The rule that makes it work
int sem_init(sem_t *sem, int pshared, unsigned value) initializes a semaphore stored at the address you give. The pshared argument decides who may use it:
0 means the semaphore is shared between the threads of one process. It may live anywhere, such as a global variable.
Nonzero means it may be shared between processes, and then
semmust point into memory that the processes share: aMAP_SHAREDmapping, a POSIX shared memory object or System V shared memory.
If you pass a nonzero pshared but place the sem_t in ordinary private memory, there is no error. After a fork() each process has its own copy of the semaphore, the two never interact, and the program deadlocks or races with no diagnostic. That mismatch is the main hazard, and it is invisible in the source unless you check where the memory came from.
Linux supports process-shared unnamed semaphores directly, since they are built on futexes in the shared page. Initialize each semaphore once, before the other process uses it, and destroy it once with sem_destroy() when no one is waiting.
The data structure
A bounded buffer needs three semaphores:
| Semaphore | Initial value | Meaning |
|---|---|---|
empty | N (the capacity) | Free slots: the producer waits on it before writing |
full | 0 | Filled slots: the consumer waits on it before reading |
mutex | 1 | Protects the indexes when there is more than one producer or consumer |
With exactly one producer and one consumer, the mutex is not needed, because each index has a single writer. It is included here because the general case is the useful pattern, and it costs one pair of calls.
The program
#define _GNU_SOURCE
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>
#define SLOTS 4
#define ITEMS 10
struct shared {
sem_t empty;
sem_t full;
sem_t mutex;
int in;
int out;
int buf[SLOTS];
};
static void produce(struct shared *s)
{
for (int i = 1; i <= ITEMS; i++) {
sem_wait(&s->empty); /* wait for a free slot */
sem_wait(&s->mutex);
s->buf[s->in] = i * i; /* item: the square of i */
s->in = (s->in + 1) % SLOTS;
sem_post(&s->mutex);
sem_post(&s->full); /* announce one more item */
}
}
static long consume(struct shared *s)
{
long total = 0;
for (int i = 1; i <= ITEMS; i++) {
int item;
sem_wait(&s->full); /* wait for an item */
sem_wait(&s->mutex);
item = s->buf[s->out];
s->out = (s->out + 1) % SLOTS;
sem_post(&s->mutex);
sem_post(&s->empty); /* announce one more free slot */
printf("consumed %d\n", item);
total += item;
}
return total;
}
int main(void)
{
struct shared *s = mmap(NULL, sizeof *s, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
pid_t pid;
if (s == MAP_FAILED) {
perror("mmap");
return 1;
}
sem_init(&s->empty, 1, SLOTS); /* pshared = 1: across processes */
sem_init(&s->full, 1, 0);
sem_init(&s->mutex, 1, 1);
s->in = s->out = 0;
pid = fork();
if (pid == 0) {
produce(s);
_exit(0);
}
printf("total %ld\n", consume(s));
waitpid(pid, NULL, 0);
sem_destroy(&s->empty);
sem_destroy(&s->full);
sem_destroy(&s->mutex);
munmap(s, sizeof *s);
return 0;
}The producer runs in the child and the consumer in the parent, and only the consumer prints, so the output order is deterministic whatever the scheduler does.
consumed 1
consumed 4
consumed 9
consumed 16
consumed 25
consumed 36
consumed 49
consumed 64
consumed 81
consumed 100
total 385The sum of the squares 1 through 10 is 385. If the buffer had no semaphores, the consumer could read a slot before it was written, or the producer could overwrite one that had not been read, and the printed values would be wrong or repeated. MAP_ANONYMOUS | MAP_SHARED creates memory that a forked child shares with its parent, with no name and no file, and it vanishes when both unmap it or exit.
Why the order of the waits matters
The producer waits on empty before taking the mutex. Swapping the order, mutex first and then empty, causes a deadlock whenever the buffer is full: the producer holds the mutex while waiting for a free slot, and the consumer needs the mutex to free one. The rule is general: wait on resource-counting semaphores first, then take the mutex for the shortest possible critical section, and release in the reverse order.
The sem_post() calls come after the data change. The producer posts full only after it has written the item and released the mutex, so a consumer that wakes sees a complete item. The semaphore operations also act as memory barriers, which is why the plain int array needs no atomics: the post and the matching wait synchronize the data between processes.
Using it with unrelated processes
MAP_ANONYMOUS sharing works only between a process and its descendants. For unrelated processes, place the same structure in a POSIX shared memory object and let one process initialize it:
int fd = shm_open("/bounded_buf", O_CREAT | O_EXCL | O_RDWR, 0600);
if (fd != -1) {
/* we are the creator: size it, map it, then initialize the semaphores */
ftruncate(fd, sizeof(struct shared));
s = mmap(NULL, sizeof *s, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
sem_init(&s->empty, 1, SLOTS);
sem_init(&s->full, 1, 0);
sem_init(&s->mutex, 1, 1);
} else if (errno == EEXIST) {
/* open the existing object, map it, and do NOT initialize again */
}The danger here is the race between the creator initializing and another process using the memory too early. Re-initializing a semaphore that someone is waiting on is undefined. Use a handshake, such as a ready flag set with a release store after initialization, or a named semaphore as a start gate. Opening with O_EXCL identifies the single creator, and a second sem_init() on a live semaphore is the bug to avoid. Share memory between processes with shm_open and mmap shows the ready-flag pattern.
Destroying
sem_destroy() makes the semaphore unusable. Destroying one that has waiters is undefined, so destroy only after all users are finished, which in this program means after waitpid(). For a shared object, the last process to leave calls it, and the object itself is removed with shm_unlink(). If you skip sem_destroy() on Linux the program still works, since there is no kernel resource behind an unnamed semaphore, but a debugging tool or a different platform may complain, and the call documents ownership.
Failures to expect
sem_init() returns -1 with EINVAL if value exceeds SEM_VALUE_MAX, 2,147,483,647 on Linux, and with ENOSYS on a platform without process-shared support, which Linux does not hit. sem_wait() fails with EINTR if a handler interrupts it, as described in write EINTR-safe wrappers for read, write and other blocking calls, so wrap it in a retry loop in programs that handle signals.
A process that dies between sem_wait(&s->empty) and sem_post(&s->full) leaves the counts out of balance, and its partner blocks forever. POSIX semaphores have no undo, so for crash tolerance give the waits a timeout with sem_timedwait() and a recovery plan, or use System V semaphores with SEM_UNDO.
Threads in the same process
The same code works with pshared 0 between threads, and the structure can be a plain global. For threads, a pthread_mutex_t with two condition variables is the more common design, since it reports errors in more detail and supports broadcast. The semaphore version is popular because the counting is built into the primitive and the code reads close to the textbook algorithm.
When not to use this
If the processes are unrelated and short-lived, named semaphores avoid the initialization race. If you need more than one producer or consumer with fairness guarantees, or you want the buffer to survive a crash of one side, a message queue does it for you. And if neither side can afford to block on a dead partner, the semaphore design needs more machinery than the problem justifies.


