Skip to content

sem_wait() / sem_post()

Purpose

Performs decrement/wait and increment/signal operations on a POSIX semaphore.

#include <semaphore.h>

Prototype

int sem_wait(sem_t *sem);
int sem_post(sem_t *sem);

Parameters

  • sem: pointer to a POSIX semaphore.

Return Value

  • Success: returns 0.
  • Failure: returns -1 and sets errno.

Minimal Example

sem_wait(&shared->items);
/* consume one item */
sem_post(&shared->spaces);

Common Pitfalls

  • sem_wait() can be interrupted by a signal and fail with EINTR.
  • sem_post() is used to wake waiters.
  • Keep semaphore ownership and shared memory lifetime clearly defined.