Timers and Sleeping 511
fd = timerfd_create(CLOCK_REALTIME, 0);
if (fd == -1)
errExit("timerfd_create");
if (timerfd_settime(fd, 0, &ts, NULL) == -1)
errExit("timerfd_settime");
if (clock_gettime(CLOCK_MONOTONIC, &start) == -1)
errExit("clock_gettime");
for (totalExp = 0; totalExp < maxExp;) {
/* Read number of expirations on the timer, and then display
time elapsed since timer was started, followed by number
of expirations read and total expirations so far. */
s = read(fd, &numExp, sizeof(uint64_t));
if (s != sizeof(uint64_t))
errExit("read");
totalExp += numExp;
if (clock_gettime(CLOCK_MONOTONIC, &now) == -1)
errExit("clock_gettime");
secs = now.tv_sec - start.tv_sec;
nanosecs = now.tv_nsec - start.tv_nsec;
if (nanosecs < 0) {
secs--;
nanosecs += 1000000000;
}
printf("%d.%03d: expirations read: %llu; total=%llu\n",
secs, (nanosecs + 500000) / 1000000,
(unsigned long long) numExp, (unsigned long long) totalExp);
}
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––– timers/demo_timerfd.c
23.8 Summary..................................................................................................................
A process can use setitimer() or alarm() to set a timer, so that it receives a signal after
the passage of a specified amount of real or process time. One use of timers is to
set an upper limit on the time for which a system call can block.
Applications that need to suspend execution for a specified interval of real
time can use a variety of sleep functions for this purpose.
Linux 2.6 implements the POSIX.1b extensions that define an API for high-
precision clocks and timers. POSIX.1b timers provide a number of advantages over
traditional (setitimer()) UNIX timers. We can: create multiple timers; choose the signal
that is delivered on timer expiration; retrieve the timer overrun count in order to