1TIMERFD_CREATE(2)          Linux Programmer's Manual         TIMERFD_CREATE(2)
2
3
4

NAME

6       timerfd_create,  timerfd_settime,  timerfd_gettime - timers that notify
7       via file descriptors
8

SYNOPSIS

10       #include <sys/timerfd.h>
11
12       int timerfd_create(int clockid, int flags);
13
14       int timerfd_settime(int fd, int flags,
15                           const struct itimerspec *new_value,
16                           struct itimerspec *old_value);
17
18       int timerfd_gettime(int fd, struct itimerspec *curr_value);
19

DESCRIPTION

21       These system calls create and operate on a timer  that  delivers  timer
22       expiration notifications via a file descriptor.  They provide an alter‐
23       native to the use of setitimer(2) or timer_create(2), with  the  advan‐
24       tage  that  the file descriptor may be monitored by select(2), poll(2),
25       and epoll(7).
26
27       The use of these  three  system  calls  is  analogous  to  the  use  of
28       timer_create(2),  timer_settime(2), and timer_gettime(2).  (There is no
29       analog of timer_getoverrun(2), since that functionality is provided  by
30       read(2), as described below.)
31
32   timerfd_create()
33       timerfd_create()  creates  a  new  timer object, and returns a file de‐
34       scriptor that refers to that timer.  The clockid argument specifies the
35       clock  that  is used to mark the progress of the timer, and must be one
36       of the following:
37
38       CLOCK_REALTIME
39              A settable system-wide real-time clock.
40
41       CLOCK_MONOTONIC
42              A nonsettable monotonically increasing clock that measures  time
43              from some unspecified point in the past that does not change af‐
44              ter system startup.
45
46       CLOCK_BOOTTIME (Since Linux 3.15)
47              Like CLOCK_MONOTONIC, this is a monotonically increasing  clock.
48              However,  whereas the CLOCK_MONOTONIC clock does not measure the
49              time while a system is suspended, the CLOCK_BOOTTIME clock  does
50              include  the time during which the system is suspended.  This is
51              useful  for  applications  that  need   to   be   suspend-aware.
52              CLOCK_REALTIME is not suitable for such applications, since that
53              clock is affected by discontinuous changes to the system clock.
54
55       CLOCK_REALTIME_ALARM (since Linux 3.11)
56              This clock is like CLOCK_REALTIME, but will wake the  system  if
57              it  is suspended.  The caller must have the CAP_WAKE_ALARM capa‐
58              bility in order to set a timer against this clock.
59
60       CLOCK_BOOTTIME_ALARM (since Linux 3.11)
61              This clock is like CLOCK_BOOTTIME, but will wake the  system  if
62              it  is suspended.  The caller must have the CAP_WAKE_ALARM capa‐
63              bility in order to set a timer against this clock.
64
65       See clock_getres(2) for some further details on the above clocks.
66
67       The current value of each  of  these  clocks  can  be  retrieved  using
68       clock_gettime(2).
69
70       Starting with Linux 2.6.27, the following values may be bitwise ORed in
71       flags to change the behavior of timerfd_create():
72
73       TFD_NONBLOCK  Set the O_NONBLOCK file status flag on the open file  de‐
74                     scription  (see  open(2)) referred to by the new file de‐
75                     scriptor.  Using this flag saves extra calls to  fcntl(2)
76                     to achieve the same result.
77
78       TFD_CLOEXEC   Set  the  close-on-exec (FD_CLOEXEC) flag on the new file
79                     descriptor.  See the description of the O_CLOEXEC flag in
80                     open(2) for reasons why this may be useful.
81
82       In  Linux  versions up to and including 2.6.26, flags must be specified
83       as zero.
84
85   timerfd_settime()
86       timerfd_settime() arms (starts) or disarms (stops) the  timer  referred
87       to by the file descriptor fd.
88
89       The  new_value  argument  specifies the initial expiration and interval
90       for the timer.  The itimerspec structure used for  this  argument  con‐
91       tains  two  fields,  each of which is in turn a structure of type time‐
92       spec:
93
94           struct timespec {
95               time_t tv_sec;                /* Seconds */
96               long   tv_nsec;               /* Nanoseconds */
97           };
98
99           struct itimerspec {
100               struct timespec it_interval;  /* Interval for periodic timer */
101               struct timespec it_value;     /* Initial expiration */
102           };
103
104       new_value.it_value specifies the initial expiration of  the  timer,  in
105       seconds and nanoseconds.  Setting either field of new_value.it_value to
106       a  nonzero  value   arms   the   timer.    Setting   both   fields   of
107       new_value.it_value to zero disarms the timer.
108
109       Setting  one  or both fields of new_value.it_interval to nonzero values
110       specifies the period, in seconds and nanoseconds,  for  repeated  timer
111       expirations   after   the   initial  expiration.   If  both  fields  of
112       new_value.it_interval are zero, the timer expires  just  once,  at  the
113       time specified by new_value.it_value.
114
115       By  default,  the initial expiration time specified in new_value is in‐
116       terpreted relative to the current time on the timer's clock at the time
117       of  the call (i.e., new_value.it_value specifies a time relative to the
118       current value of the clock specified by clockid).  An absolute  timeout
119       can be selected via the flags argument.
120
121       The flags argument is a bit mask that can include the following values:
122
123       TFD_TIMER_ABSTIME
124              Interpret new_value.it_value as an absolute value on the timer's
125              clock.  The timer will expire when  the  value  of  the  timer's
126              clock reaches the value specified in new_value.it_value.
127
128       TFD_TIMER_CANCEL_ON_SET
129              If  this  flag is specified along with TFD_TIMER_ABSTIME and the
130              clock for this timer is CLOCK_REALTIME or  CLOCK_REALTIME_ALARM,
131              then mark this timer as cancelable if the real-time clock under‐
132              goes a discontinuous change (settimeofday(2),  clock_settime(2),
133              or  similar).   When  such  changes  occur,  a current or future
134              read(2) from the file descriptor will fail with the error  ECAN‐
135              CELED.
136
137       If  the  old_value  argument is not NULL, then the itimerspec structure
138       that it points to is used to return the setting of the timer  that  was
139       current  at  the  time of the call; see the description of timerfd_get‐
140       time() following.
141
142   timerfd_gettime()
143       timerfd_gettime() returns, in curr_value, an itimerspec structure  that
144       contains  the  current setting of the timer referred to by the file de‐
145       scriptor fd.
146
147       The it_value field returns the amount of time until the timer will next
148       expire.   If  both fields of this structure are zero, then the timer is
149       currently disarmed.  This field always contains a relative  value,  re‐
150       gardless  of whether the TFD_TIMER_ABSTIME flag was specified when set‐
151       ting the timer.
152
153       The it_interval field returns the  interval  of  the  timer.   If  both
154       fields of this structure are zero, then the timer is set to expire just
155       once, at the time specified by curr_value.it_value.
156
157   Operating on a timer file descriptor
158       The file descriptor returned by timerfd_create() supports the following
159       additional operations:
160
161       read(2)
162              If  the  timer  has  already expired one or more times since its
163              settings were last modified using  timerfd_settime(),  or  since
164              the  last  successful  read(2), then the buffer given to read(2)
165              returns an unsigned 8-byte  integer  (uint64_t)  containing  the
166              number  of  expirations that have occurred.  (The returned value
167              is in host byte order—that is, the native byte order  for  inte‐
168              gers on the host machine.)
169
170              If  no  timer  expirations  have  occurred  at  the  time of the
171              read(2), then the call either blocks until the next timer  expi‐
172              ration,  or  fails  with the error EAGAIN if the file descriptor
173              has been made nonblocking (via the use of the  fcntl(2)  F_SETFL
174              operation to set the O_NONBLOCK flag).
175
176              A  read(2)  fails  with the error EINVAL if the size of the sup‐
177              plied buffer is less than 8 bytes.
178
179              If the associated clock is either CLOCK_REALTIME or  CLOCK_REAL‐
180              TIME_ALARM,  the  timer is absolute (TFD_TIMER_ABSTIME), and the
181              flag  TFD_TIMER_CANCEL_ON_SET   was   specified   when   calling
182              timerfd_settime(),  then  read(2) fails with the error ECANCELED
183              if the real-time clock undergoes a discontinuous change.   (This
184              allows  the  reading  application to discover such discontinuous
185              changes to the clock.)
186
187              If the associated clock is either CLOCK_REALTIME or  CLOCK_REAL‐
188              TIME_ALARM,  the  timer is absolute (TFD_TIMER_ABSTIME), and the
189              flag TFD_TIMER_CANCEL_ON_SET  was  not  specified  when  calling
190              timerfd_settime(),  then  a discontinuous negative change to the
191              clock (e.g., clock_settime(2)) may cause read(2) to unblock, but
192              return  a  value of 0 (i.e., no bytes read), if the clock change
193              occurs after the time expired, but before  the  read(2)  on  the
194              file descriptor.
195
196       poll(2), select(2) (and similar)
197              The file descriptor is readable (the select(2) readfds argument;
198              the poll(2) POLLIN flag) if one or more timer  expirations  have
199              occurred.
200
201              The file descriptor also supports the other file-descriptor mul‐
202              tiplexing APIs: pselect(2), ppoll(2), and epoll(7).
203
204       ioctl(2)
205              The following timerfd-specific command is supported:
206
207              TFD_IOC_SET_TICKS (since Linux 3.17)
208                     Adjust the number of  timer  expirations  that  have  oc‐
209                     curred.   The  argument  is a pointer to a nonzero 8-byte
210                     integer (uint64_t*) containing the new number of  expira‐
211                     tions.   Once  the number is set, any waiter on the timer
212                     is woken up.  The only purpose of this command is to  re‐
213                     store  the  expirations for the purpose of checkpoint/re‐
214                     store.  This operation is available only  if  the  kernel
215                     was configured with the CONFIG_CHECKPOINT_RESTORE option.
216
217       close(2)
218              When  the  file  descriptor  is  no longer required it should be
219              closed.  When all file  descriptors  associated  with  the  same
220              timer object have been closed, the timer is disarmed and its re‐
221              sources are freed by the kernel.
222
223   fork(2) semantics
224       After a fork(2), the child inherits a copy of the file descriptor  cre‐
225       ated  by  timerfd_create().  The file descriptor refers to the same un‐
226       derlying timer object as the corresponding file descriptor in the  par‐
227       ent,  and  read(2)s  in the child will return information about expira‐
228       tions of the timer.
229
230   execve(2) semantics
231       A file descriptor created by timerfd_create() is preserved  across  ex‐
232       ecve(2),  and  continues to generate timer expirations if the timer was
233       armed.
234

RETURN VALUE

236       On success, timerfd_create() returns a new file descriptor.  On  error,
237       -1 is returned and errno is set to indicate the error.
238
239       timerfd_settime()  and  timerfd_gettime() return 0 on success; on error
240       they return -1, and set errno to indicate the error.
241

ERRORS

243       timerfd_create() can fail with the following errors:
244
245       EINVAL The clockid is not valid.
246
247       EINVAL flags is invalid; or, in Linux 2.6.26 or earlier, flags is  non‐
248              zero.
249
250       EMFILE The per-process limit on the number of open file descriptors has
251              been reached.
252
253       ENFILE The system-wide limit on the total number of open files has been
254              reached.
255
256       ENODEV Could not mount (internal) anonymous inode device.
257
258       ENOMEM There was insufficient kernel memory to create the timer.
259
260       EPERM  clockid was CLOCK_REALTIME_ALARM or CLOCK_BOOTTIME_ALARM but the
261              caller did not have the CAP_WAKE_ALARM capability.
262
263       timerfd_settime() and timerfd_gettime() can fail with the following er‐
264       rors:
265
266       EBADF  fd is not a valid file descriptor.
267
268       EFAULT new_value, old_value, or curr_value is not valid a pointer.
269
270       EINVAL fd is not a valid timerfd file descriptor.
271
272       timerfd_settime() can also fail with the following errors:
273
274       ECANCELED
275              See NOTES.
276
277       EINVAL new_value  is not properly initialized (one of the tv_nsec falls
278              outside the range zero to 999,999,999).
279
280       EINVAL flags is invalid.
281

VERSIONS

283       These system calls are available on Linux since kernel 2.6.25.  Library
284       support is provided by glibc since version 2.8.
285

CONFORMING TO

287       These system calls are Linux-specific.
288

NOTES

290       Suppose  the  following  scenario  for  CLOCK_REALTIME  or  CLOCK_REAL‐
291       TIME_ALARM timer that was created with timerfd_create():
292
293       (a) The  timer  has   been   started   (timerfd_settime())   with   the
294           TFD_TIMER_ABSTIME and TFD_TIMER_CANCEL_ON_SET flags;
295
296       (b) A discontinuous change (e.g., settimeofday(2)) is subsequently made
297           to the CLOCK_REALTIME clock; and
298
299       (c) the caller once more calls timerfd_settime()  to  rearm  the  timer
300           (without first doing a read(2) on the file descriptor).
301
302       In this case the following occurs:
303
304       • The  timerfd_settime() returns -1 with errno set to ECANCELED.  (This
305         enables the caller to know that the previous timer was affected by  a
306         discontinuous change to the clock.)
307
308       • The  timer  is successfully rearmed with the settings provided in the
309         second timerfd_settime() call.  (This was probably an  implementation
310         accident, but won't be fixed now, in case there are applications that
311         depend on this behaviour.)
312

BUGS

314       Currently, timerfd_create() supports fewer  types  of  clock  IDs  than
315       timer_create(2).
316

EXAMPLES

318       The  following  program creates a timer and then monitors its progress.
319       The program accepts up to three command-line arguments.  The first  ar‐
320       gument  specifies  the  number of seconds for the initial expiration of
321       the timer.  The second argument specifies the interval for  the  timer,
322       in  seconds.  The third argument specifies the number of times the pro‐
323       gram should allow the timer to expire before terminating.   The  second
324       and third command-line arguments are optional.
325
326       The following shell session demonstrates the use of the program:
327
328           $ a.out 3 1 100
329           0.000: timer started
330           3.000: read: 1; total=1
331           4.000: read: 1; total=2
332           ^Z                  # type control-Z to suspend the program
333           [1]+  Stopped                 ./timerfd3_demo 3 1 100
334           $ fg                # Resume execution after a few seconds
335           a.out 3 1 100
336           9.660: read: 5; total=7
337           10.000: read: 1; total=8
338           11.000: read: 1; total=9
339           ^C                  # type control-C to suspend the program
340
341   Program source
342
343       #include <sys/timerfd.h>
344       #include <time.h>
345       #include <unistd.h>
346       #include <inttypes.h>      /* Definition of PRIu64 */
347       #include <stdlib.h>
348       #include <stdio.h>
349       #include <stdint.h>        /* Definition of uint64_t */
350
351       #define handle_error(msg) \
352               do { perror(msg); exit(EXIT_FAILURE); } while (0)
353
354       static void
355       print_elapsed_time(void)
356       {
357           static struct timespec start;
358           struct timespec curr;
359           static int first_call = 1;
360           int secs, nsecs;
361
362           if (first_call) {
363               first_call = 0;
364               if (clock_gettime(CLOCK_MONOTONIC, &start) == -1)
365                   handle_error("clock_gettime");
366           }
367
368           if (clock_gettime(CLOCK_MONOTONIC, &curr) == -1)
369               handle_error("clock_gettime");
370
371           secs = curr.tv_sec - start.tv_sec;
372           nsecs = curr.tv_nsec - start.tv_nsec;
373           if (nsecs < 0) {
374               secs--;
375               nsecs += 1000000000;
376           }
377           printf("%d.%03d: ", secs, (nsecs + 500000) / 1000000);
378       }
379
380       int
381       main(int argc, char *argv[])
382       {
383           struct itimerspec new_value;
384           int max_exp, fd;
385           struct timespec now;
386           uint64_t exp, tot_exp;
387           ssize_t s;
388
389           if ((argc != 2) && (argc != 4)) {
390               fprintf(stderr, "%s init-secs [interval-secs max-exp]\n",
391                       argv[0]);
392               exit(EXIT_FAILURE);
393           }
394
395           if (clock_gettime(CLOCK_REALTIME, &now) == -1)
396               handle_error("clock_gettime");
397
398           /* Create a CLOCK_REALTIME absolute timer with initial
399              expiration and interval as specified in command line */
400
401           new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
402           new_value.it_value.tv_nsec = now.tv_nsec;
403           if (argc == 2) {
404               new_value.it_interval.tv_sec = 0;
405               max_exp = 1;
406           } else {
407               new_value.it_interval.tv_sec = atoi(argv[2]);
408               max_exp = atoi(argv[3]);
409           }
410           new_value.it_interval.tv_nsec = 0;
411
412           fd = timerfd_create(CLOCK_REALTIME, 0);
413           if (fd == -1)
414               handle_error("timerfd_create");
415
416           if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
417               handle_error("timerfd_settime");
418
419           print_elapsed_time();
420           printf("timer started\n");
421
422           for (tot_exp = 0; tot_exp < max_exp;) {
423               s = read(fd, &exp, sizeof(uint64_t));
424               if (s != sizeof(uint64_t))
425                   handle_error("read");
426
427               tot_exp += exp;
428               print_elapsed_time();
429               printf("read: %" PRIu64 "; total=%" PRIu64 "\n", exp, tot_exp);
430           }
431
432           exit(EXIT_SUCCESS);
433       }
434

SEE ALSO

436       eventfd(2),  poll(2),  read(2),  select(2),  setitimer(2), signalfd(2),
437       timer_create(2), timer_gettime(2), timer_settime(2), epoll(7), time(7)
438

COLOPHON

440       This page is part of release 5.10 of the Linux  man-pages  project.   A
441       description  of  the project, information about reporting bugs, and the
442       latest    version    of    this    page,    can     be     found     at
443       https://www.kernel.org/doc/man-pages/.
444
445
446
447Linux                             2020-08-13                 TIMERFD_CREATE(2)
Impressum