timers/ptmr_null_evp.c

This is timers/ptmr_null_evp.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 23-3 (page 512).

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 timers/ptmr_null_evp.c

  Cover of The Linux Programming Interface

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

/* ptmr_null_evp.c

   A program to demonstrate POSIX timer defaults when the 'evp' argument
   of timer_create() is specified as NULL.

   Kernel support for Linux timers is provided since Linux 2.6. On older
   systems, an incomplete user-space implementation of POSIX timers
   was provided in glibc.
*/
#define _POSIX_C_SOURCE 199309
#include <signal.h>
#include <time.h>
#include "curr_time.h"          /* Declaration of currTime() */
#include "tlpi_hdr.h"
static void
handler(int sig, siginfo_t *si, void *uc)
{
    printf("[%s] Got signal %d\n", currTime("%T"), sig);
    printf("    sival_int          = %d\n", si->si_value.sival_int);
#ifdef __linux__
    printf("    si_overrun         = %d\n", si->si_overrun);
#endif
    printf("    timer_getoverrun() = %d\n",
            timer_getoverrun((timer_t) si->si_value.sival_ptr));
}
int
main(int argc, char *argv[])
{
    if (argc < 2)
        usageErr("%s secs [nsecs [int-secs [int-nsecs]]]\n", argv[0]);

    struct sigaction sa;
    sa.sa_flags = SA_SIGINFO;
    sa.sa_sigaction = handler;
    sigemptyset(&sa.sa_mask);
    if (sigaction(SIGALRM, &sa, NULL) == -1)
        errExit("sigaction");

    timer_t tid;
    if (timer_create(CLOCK_REALTIME, NULL, &tid) == -1)
        errExit("timer_create");
    printf("timer ID = %ld\n", (long) tid);

    struct itimerspec ts;
    ts.it_value.tv_sec = atoi(argv[1]);
    ts.it_value.tv_nsec = (argc > 2) ? atoi(argv[2]) : 0;
    ts.it_interval.tv_sec = (argc > 3) ? atoi(argv[3]) : 0;
    ts.it_interval.tv_nsec = (argc > 4) ? atoi(argv[4]) : 0;
    if (timer_settime(tid, 0, &ts, NULL) == -1)
        errExit("timer_settime");

    for (int j = 0; ; j++)
        pause();
}

 

Download timers/ptmr_null_evp.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