Synchronize Processes with Named POSIX Semaphores
Synchronize unrelated processes with named POSIX semaphores: sem_open, sem_wait, sem_post, a ping and pong example, sem_timedwait and sem_unlink on Linux 6.12.

When two processes must take turns, or one must wait until the other has finished a step, a semaphore is the plain tool. It is a counter that sem_wait() decrements, blocking at zero, and sem_post() increments. A named POSIX semaphore has a name like a file, so processes that do not share an ancestor can find the same one. This post uses them for a turn-taking example, a timeout and the cleanup rules, on Linux 6.12 with glibc 2.41, following sem_overview(7) and sem_open(3).
Semaphores move no data. They usually guard shared memory. The variant for related processes that share a mapping is in use unnamed semaphores in shared memory with sem_init.
The model
A semaphore holds a non-negative integer.
sem_wait(s)decrements it. If the value is zero, the call blocks until another process posts.sem_post(s)increments it and wakes one waiter.sem_trywait(s)decrements if possible, or fails at once withEAGAIN.sem_timedwait(s, &deadline)waits until an absolute time and fails withETIMEDOUT.
A semaphore with initial value 1 acts as a mutex: wait to enter, post to leave. With initial value 0 it is a signal: one side posts when something is ready, and the other waits. Unlike a mutex, any process may post, not only the one that waited, which is what makes it suitable for signaling between processes.
Creating and opening
sem_open(name, oflag, mode, value) creates a semaphore when oflag includes O_CREAT, setting its initial value, or opens an existing one. Names follow the same rule as shared memory: a leading slash and no other slash, such as /ping. On Linux each appears as a file /dev/shm/sem.ping. If the semaphore exists when you pass O_CREAT, mode and value are ignored, which is how two programs can both pass the same arguments and let the first one win. With O_CREAT | O_EXCL, an existing name makes the call fail with EEXIST.
The return type is sem_t *, and failure returns SEM_FAILED, not NULL.
When finished, sem_close() ends your use of the handle, and sem_unlink() removes the name. Like other POSIX IPC objects, the semaphore persists after the creator exits unless someone unlinks it.
Taking turns: ping and pong
This program forks, and the parent and child print alternately. Two semaphores enforce the order: the parent waits on pong_turn before printing, the child waits on ping_turn. Each posts the other's semaphore when it finishes a step. The fork() shares the opened handles, so no name lookup is needed in the child, though the semaphores are still named so that you could run the two roles as separate programs.
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#define ROUNDS 3
int main(void)
{
sem_t *ping, *pong;
pid_t pid;
sem_unlink("/pp_ping"); /* remove leftovers from a crash */
sem_unlink("/pp_pong");
ping = sem_open("/pp_ping", O_CREAT | O_EXCL, 0600, 1); /* parent goes first */
pong = sem_open("/pp_pong", O_CREAT | O_EXCL, 0600, 0);
if (ping == SEM_FAILED || pong == SEM_FAILED) {
perror("sem_open");
return 1;
}
pid = fork();
if (pid == 0) {
for (int i = 0; i < ROUNDS; i++) {
sem_wait(pong);
printf("pong %d\n", i + 1);
fflush(stdout);
sem_post(ping);
}
_exit(0);
}
for (int i = 0; i < ROUNDS; i++) {
sem_wait(ping);
printf("ping %d\n", i + 1);
fflush(stdout);
sem_post(pong);
}
waitpid(pid, NULL, 0);
sem_close(ping);
sem_close(pong);
sem_unlink("/pp_ping");
sem_unlink("/pp_pong");
return 0;
}ping 1
pong 1
ping 2
pong 2
ping 3
pong 3Only one process can proceed at a time, whatever the scheduler does, because the value of each semaphore is 1 for exactly one of them. The fflush() calls matter: with standard output redirected to a pipe or file the two processes buffer separately, and output would appear in the wrong order despite correct synchronization. The synchronization controls when each printf() runs, and the flush makes the text leave the process then.
The sem_unlink() calls at the start clear stale semaphores from an earlier crash. Without them O_EXCL would fail with EEXIST after an unclean exit.
Waiting with a timeout
A process that waits forever on a semaphore whose partner crashed hangs. sem_timedwait() bounds the wait. Its deadline is absolute, measured on CLOCK_REALTIME, not a duration, so you compute "now plus the delay".
#include <errno.h>
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void)
{
sem_t *s;
struct timespec deadline;
sem_unlink("/tw_demo");
s = sem_open("/tw_demo", O_CREAT | O_EXCL, 0600, 0); /* nobody will post */
if (s == SEM_FAILED) {
perror("sem_open");
return 1;
}
clock_gettime(CLOCK_REALTIME, &deadline);
deadline.tv_sec += 1;
if (sem_timedwait(s, &deadline) == -1) {
printf("sem_timedwait: %s\n", strerror(errno));
}
if (sem_trywait(s) == -1)
printf("sem_trywait: %s\n", strerror(errno));
sem_close(s);
sem_unlink("/tw_demo");
return 0;
}sem_timedwait: Connection timed out
sem_trywait: Resource temporarily unavailableThe message for ETIMEDOUT is the C library's generic text and does not mean a network connection. glibc 2.30 added sem_clockwait(), which accepts a CLOCK_MONOTONIC deadline, the better choice because a change of the system clock cannot shorten or lengthen the wait.
Interruption
sem_wait() fails with EINTR when a signal handler installed without SA_RESTART interrupts it. Since Linux 2.6.22 the call is restarted when the flag is set, but portable code cannot assume that, so a correct wait loops:
int r;
do {
r = sem_wait(s);
} while (r == -1 && errno == EINTR);Write EINTR-safe wrappers for read, write and other blocking calls develops the same idea for other calls.
Crash behavior
POSIX semaphores have no equivalent of System V's SEM_UNDO. If a process dies after sem_wait() and before sem_post(), the count stays decremented and any other waiter blocks forever. A semaphore used as a mutex is therefore dangerous across processes that can crash. Use a timeout and recovery logic, or a robust mutex (PTHREAD_MUTEX_ROBUST with PTHREAD_PROCESS_SHARED), which reports EOWNERDEAD to the next locker. Use System V semaphores with semop and SEM_UNDO shows the other design.
Inspecting a semaphore
sem_getvalue() stores the current count in an int. When processes are blocked on the semaphore, POSIX allows a negative count and Linux reports 0. It is for diagnostics only, since the value can change before you act on it. A check of "is it zero?" followed by an action is a race, so use sem_trywait(), which tests and decrements in one step.
From the shell, ls -l /dev/shm/sem.* lists named semaphores, and rm removes one. A semaphore file holds its value in the shared mapping used by sem_open().
Choosing the initial value
The initial value encodes what the semaphore means, so choose it deliberately. A value of 1 turns it into a lock. A value of 0 makes it an event that the consumer waits for and the producer posts. A value of N makes it a pool of N identical resources, such as N worker slots or N connection tokens, and each user waits to take one and posts to return it. A common slip is to create a signaling semaphore with value 1, so the first waiter runs through before anything was ready, and the bug appears only on the first iteration after every restart.
When not to use named semaphores
For threads of one process, a pthread_mutex_t or condition variable is cheaper and reports errors better. For processes related by fork() that already share a mapping, an unnamed semaphore avoids names and cleanup. If a crashed holder must not block everyone, use a robust mutex or the System V semaphore with undo. And for messaging, which a semaphore cannot do, use a message queue.


