SEM_TIMEDWAIT(3POSIX)

πŸ’– SEM_TIMEDWAIT πŸ’– β€” the POSIX Programmer's Manual, bestie edition

okay so before we even start: this page lives in the POSIX Programmer's Manual (that's the 3POSIX in the corner, iykyk). And a lil heads up 🫢 β€” the Linux implementation of this interface may differ from what's written here (so pls consult the corresponding Linux manual page for the details of Linux behavior), or the interface might not even be implemented on Linux at all. just so you know. πŸ’…


✨ NAME ✨

sem_timedwait β€” lock a semaphore

the way it just... locks a semaphore. iconic behavior honestly. πŸ”’


🌸 SYNOPSIS 🌸

#include <semaphore.h>
#include <time.h>

int sem_timedwait(sem_t *restrict sem,
    const struct timespec *restrict abstime);

πŸ¦‹ DESCRIPTION πŸ¦‹

so sem_timedwait() is gonna lock the semaphore that sem points to, exactly like sem_wait() does. same energy. BUT πŸ’€ β€” and this is the whole point of her existence β€” if the semaphore can't be locked without waiting for another process or thread to unlock it by doing a sem_post(), then this wait gets terminated when the specified timeout expires. she does not wait forever. she has boundaries. periodt.

the timeout expires when the absolute time given by abstime passes, measured by the clock that timeouts are based on (like, when the value of that clock equals or exceeds abstime). it ALSO expires if the absolute time in abstime had already passed at the moment of the call. yes bestie, if you're late, you're late. πŸ•

the timeout is based on the CLOCK_REALTIME clock. the resolution of the timeout is the resolution of whatever clock it's based on. the timespec data type is defined as a structure in the <time.h> header. πŸ“–

and under no circumstance shall the function fail with a timeout if the semaphore can be locked immediately. also, the validity of abstime doesn't even need to be checked if the semaphore can be locked immediately. like, if she can get in, she's not checking the clock. she's just going. πŸ’…


πŸŽ€ RETURN VALUE πŸŽ€

sem_timedwait() returns zero if the calling process successfully did the semaphore lock operation on the semaphore designated by sem. yay!! πŸŽ‰

if the call was unsuccessful: the state of the semaphore stays unchanged, the function returns a value of -1, and it sets errno to tell you what went wrong. no vibes were harmed, but also no lock was acquired. 😭


πŸ’€ ERRORS πŸ’€

sem_timedwait() shall fail if:

  • EINVAL β€” the process or thread would have blocked, and the abstime parameter specified a nanoseconds field value less than zero or greater than or equal to 1000 million. bestie that's not a real nanosecond count, that's a cry for help.
  • ETIMEDOUT β€” the semaphore could not be locked before the specified timeout expired. she waited. she tried. the clock said no. ⏰

sem_timedwait() may fail if:

  • EDEADLK β€” a deadlock condition was detected. πŸ’€πŸ’€
  • EINTR β€” a signal interrupted this function. rude, honestly.
  • EINVAL β€” the sem argument does not refer to a valid semaphore.
okay the following sections are informative β€” meaning they're the bonus content, not the contract. but they're still cute so read them.

🌈 EXAMPLES 🌈

the program below operates on an unnamed semaphore. it expects two command-line arguments. the first argument is a seconds value used to set an alarm timer that generates a SIGALRM signal β€” and that handler does a sem_post(3) to increment the semaphore that main() is waiting on with sem_timedwait(). the second command-line argument is the length of the timeout, in seconds, for sem_timedwait(). 🧚

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <signal.h>

sem_t sem;

static void
handler(int sig)
{
    int sav_errno = errno;
    static const char info_msg[] = "sem_post() from handler\n";
    write(STDOUT_FILENO, info_msg, sizeof info_msg - 1);
    if (sem_post(&sem) == -1) {
        static const char err_msg[] = "sem_post() failed\n";
        write(STDERR_FILENO, err_msg, sizeof err_msg - 1);
        _exit(EXIT_FAILURE);
    }
    errno = sav_errno;
}

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) {
        perror("sem_init");
        exit(EXIT_FAILURE);
    }

    /* 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) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    alarm(atoi(argv[1]));

    /* Calculate relative interval as current time plus
       number of seconds given argv[2] */

    if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
        perror("clock_gettime");
        exit(EXIT_FAILURE);
    }
    ts.tv_sec += atoi(argv[2]);

    printf("main() about to call sem_timedwait()\n");
    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);
}

πŸ’… APPLICATION USAGE πŸ’…

applications using these functions may be subject to priority inversion, as discussed in the Base Definitions volume of POSIX.1‐2017, Section 3.291, Priority Inversion. yes that's a real thing, go read it. πŸ‘‘


🫢 RATIONALE 🫢

None.

(that's it. that's the rationale. she said nothing and she ate.) πŸ™ˆ


⭐ FUTURE DIRECTIONS ⭐

None.


πŸ”₯ SEE ALSO πŸ”₯

sem_post(), sem_trywait(), semctl(), semget(), semop(), time()

the Base Definitions volume of POSIX.1‐2017, Section 3.291, Priority Inversion, <semaphore.h>, <time.h>


Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


and that's the whole page bestie!! 🌸 this one came from IEEE/The Open Group, dated 2017, and it lives at SEM_TIMEDWAIT(3POSIX). go lock something. responsibly. mwah πŸ’‹βœ¨