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 from sem_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; peep signal(7) for the lore.
  • EINVAL โ€” sem is not a valid semaphore. ๐Ÿšฉ
  • EINVAL (only from sem_timedwait()) โ€” the value of abs_timeout.tv_nsecs is less than 0, or greater than or equal to 1000 million. yeah that's a whole billion nanoseconds, keep it in range.
  • ETIMEDOUT (only from sem_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
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms