psem/psem_timedwait.c

This is psem/psem_timedwait.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is the solution to Exercise 53-2 (page 1105).

The source code file is copyright 2022, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.

 

Download psem/psem_timedwait.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* psem_timedwait.c

   Decrease the value of a POSIX named semaphore using sem_timedwait().

   Usage: psem_timedwait sem-name nsecs

   On Linux, named semaphores are supported with kernel 2.6 or later, and
   a glibc that provides the NPTL threading implementation.
*/
#define _POSIX_C_SOURCE 199309
#include <semaphore.h>
#include <time.h>
#include "tlpi_hdr.h"
int
main(int argc, char *argv[])
{
    if (argc != 3 || strcmp(argv[1], "--help") == 0)
        usageErr("%s sem-name num-secs\n", argv[0]);

    sem_t *sem = sem_open(argv[1], 0);
    if (sem == SEM_FAILED)
        errExit("sem_open");

    /* sem_timedwait() expects an absolute time in its second argument.
       So we take the number of (relative) seconds specified on the
       command line, and add it to the current system time. */

    struct timespec ts;
    if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
        errExit("clock_gettime-CLOCK_REALTIME");

    ts.tv_sec += atoi(argv[2]);

    if (sem_timedwait(sem, &ts) == -1)
        errExit("sem_timedwait");

    printf("%ld sem_wait() succeeded\n", (long) getpid());
    exit(EXIT_SUCCESS);
}

 

Download psem/psem_timedwait.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1