sem_wait(3)
โจ sem_wait โ lock a semaphore (the bestie edition) โจ
okay so this is a <pink>libpthread</pink> page, manual section 3, and it's literally all about waiting on semaphores. three functions, one vibe. let's get into it ๐
๐ซถ LIBRARY ๐ซถ
POSIX threads library (libpthread, -lpthread) โ that's your link flag, don't forget it or the linker will simply end you ๐ญ
๐ธ SYNOPSIS ๐ธ
#include <semaphore.h>
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
int sem_timedwait(sem_t *restrict sem,
const struct timespec *restrict abs_timeout);
๐ Feature Test Macro Requirements for glibc ๐
(peep feature_test_macros(7) if you're nosy about the details)
sem_timedwait():
_POSIX_C_SOURCE >= 200112L
yes bestie you need that macro or glibc is gonna pretend it's never heard of sem_timedwait(). it's giving gatekeeping ๐
๐ DESCRIPTION ๐
sem_wait() decrements (aka locks) the semaphore that sem points to. if the semaphore's value is greater than zero, the decrement just happens, and the function returns immediately. slay. but if the semaphore currently has the value zero?? then the call blocks โ it sits there and waits โ until either it becomes possible to perform the decrement (i.e., the semaphore value rises above zero), or a signal handler interrupts the call. main character energy: it will simply wait its turn. โจ
sem_trywait() is the same as sem_wait(), except if the decrement cannot be immediately performed, the call returns an error (errno set to EAGAIN) instead of blocking. it's the "no thanks, not waiting around" option. iconic of it honestly.
sem_timedwait() is the same as sem_wait(), except abs_timeout specifies a limit on the amount of time that the call should block if the decrement cannot be immediately performed. the abs_timeout argument points to a timespec(3) structure that specifies an absolute timeout in seconds and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). absolute, bestie โ not relative, not "in a few seconds", like a real timestamp. do not come for me about this, it gets so many people ๐
if the timeout has already expired by the time of the call, and the semaphore could not be locked immediately, then sem_timedwait() fails with a timeout error (errno set to ETIMEDOUT).
if the operation can be performed immediately, then sem_timedwait() never fails with a timeout error, regardless of the value of abs_timeout. furthermore, the validity of abs_timeout is not checked in this case. so likeโฆ it's just not gonna look at it. it doesn't care. nothing to see here ๐ฆ
๐ RETURN VALUE ๐
all of these functions return 0 on success ๐; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.
๐ ERRORS ๐
EAGAIN(only fromsem_trywait()) โ the operation could not be performed without blocking (i.e., the semaphore currently has the value zero).EINTRโ the call was interrupted by a signal handler; peepsignal(7)for the lore.EINVALโsemis not a valid semaphore. ๐ฉEINVAL(only fromsem_timedwait()) โ the value ofabs_timeout.tv_nsecsis less than0, or greater than or equal to 1000 million. yeah that's a whole billion nanoseconds, keep it in range.ETIMEDOUT(only fromsem_timedwait()) โ the call timed out before the semaphore could be locked. sad but true โจ
๐ ATTRIBUTES ๐
want the tea on what these terms mean? see attributes(7). here's the rundown:
- Interface:
sem_wait(),sem_trywait(),sem_timedwait()- Attribute: Thread safety
- Value:
MT-Safe
so likeโฆ all three are MT-Safe. they can share. they're cool like that. ๐ซถ
โญ STANDARDS โญ
POSIX.1-2008. it's official, it's standardized, it's that girl.
๐ง HISTORY ๐ง
POSIX.1-2001. yes she's been around. veteran behavior.
๐ฅ EXAMPLES ๐ฅ
the (somewhat trivial, their words not mine) program shown below operates on an unnamed semaphore. the program expects two command-line arguments. the first argument specifies a seconds value that is used to set an alarm timer to generate a SIGALRM signal. this handler performs a sem_post(3) to increment the semaphore that is being waited on in main() using sem_timedwait(). the second command-line argument specifies the length of the timeout, in seconds, for sem_timedwait(). the following shows what happens on two different runs of the program:
$ ./a.out 2 3
About to call sem_timedwait()
sem_post() from handler
sem_timedwait() succeeded
$ ./a.out 2 1
About to call sem_timedwait()
sem_timedwait() timed out
see?? first run the alarm fired before the timeout so it succeeded ๐ฅ second run the timeout beat the alarm and it timed out ๐ literally the same code, different vibes, depending on the numbers. periodt.
๐ธ Program source ๐ธ
#include <err.h>
#include <errno.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <assert.h>
sem_t sem;
static void
handler(int sig)
{
write(STDOUT_FILENO, "sem_post() from handler\n", 24);
if (sem_post(&sem) == -1) {
write(STDERR_FILENO, "sem_post() failed\n", 18);
_exit(EXIT_FAILURE);
}
}
int
main(int argc, char *argv[])
{
struct sigaction sa;
struct timespec ts;
int s;
if (argc != 3) {
fprintf(stderr, "Usage: %s <alarm-secs> <wait-secs>\n",
argv[0]);
exit(EXIT_FAILURE);
}
if (sem_init(&sem, 0, 0) == -1)
err(EXIT_FAILURE, "sem_init");
/* Establish SIGALRM handler; set alarm timer using argv[1]. */
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGALRM, &sa, NULL) == -1)
err(EXIT_FAILURE, "sigaction");
alarm(atoi(argv[1]));
/* Calculate relative interval as current time plus
number of seconds given argv[2]. */
if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
err(EXIT_FAILURE, "clock_gettime");
ts.tv_sec += atoi(argv[2]);
printf("%s() about to call sem_timedwait()\n", __func__);
while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR)
continue; /* Restart if interrupted by handler. */
/* Check what happened. */
if (s == -1) {
if (errno == ETIMEDOUT)
printf("sem_timedwait() timed out\n");
else
perror("sem_timedwait");
} else
printf("sem_timedwait() succeeded\n");
exit((s == 0) ? EXIT_SUCCESS : EXIT_FAILURE);
}
copy it, compile it, run it, feel something ๐
๐ฆ SEE ALSO ๐ฆ
clock_gettime(2), sem_getvalue(3), sem_post(3), timespec(3), sem_overview(7), time(7)
and that's the whole page bestie!! this one's from the Linux man-pages 6.20, dated 2026-02-08, and it covers sem_wait(3) ๐ go lock a semaphore, you've got this, mwah ๐โจ
๐ฆ where this page comes from
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages 6.20
- ๐ the page's license: Linux-man-pages-copyleft
- Copyright 2006, Michael Kerrisk <mtk.manpages@gmail.com>
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms