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
34       descriptor that refers to that timer.  The clockid  argument  specifies
35       the  clock  that is used to mark the progress of the timer, and must be
36       one 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
44              after 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
74                     description  (see  open(2))  referred  to by the new file
75                     descriptor.   Using  this  flag  saves  extra  calls   to
76                     fcntl(2) 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
116       interpreted relative to the current time on the timer's  clock  at  the
117       time of the call (i.e., new_value.it_value specifies a time relative to
118       the current value of the clock  specified  by  clockid).   An  absolute
119       timeout 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
145       descriptor 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,
150       regardless  of  whether  the  TFD_TIMER_ABSTIME flag was specified when
151       setting 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
209                     occurred.   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
213                     restore   the  expirations  for  the  purpose  of  check‐
214                     point/restore.  This operation is available only  if  the
215                     kernel  was configured with the CONFIG_CHECKPOINT_RESTORE
216                     option.
217
218       close(2)
219              When the file descriptor is no  longer  required  it  should  be
220              closed.   When  all  file  descriptors  associated with the same
221              timer object have been closed, the timer  is  disarmed  and  its
222              resources are freed by the kernel.
223
224   fork(2) semantics
225       After  a fork(2), the child inherits a copy of the file descriptor cre‐
226       ated by timerfd_create().  The  file  descriptor  refers  to  the  same
227       underlying  timer  object  as  the corresponding file descriptor in the
228       parent, and read(2)s in the child will return information about expira‐
229       tions of the timer.
230
231   execve(2) semantics
232       A  file  descriptor  created  by  timerfd_create()  is preserved across
233       execve(2), and continues to generate timer expirations if the timer was
234       armed.
235

RETURN VALUE

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

ERRORS

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

VERSIONS

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

CONFORMING TO

288       These system calls are Linux-specific.
289

NOTES

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

BUGS

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

EXAMPLES

319       The following program creates a timer and then monitors  its  progress.
320       The  program  accepts  up  to  three command-line arguments.  The first
321       argument specifies the number of seconds for the initial expiration  of
322       the  timer.   The second argument specifies the interval for the timer,
323       in seconds.  The third argument specifies the number of times the  pro‐
324       gram  should  allow the timer to expire before terminating.  The second
325       and third command-line arguments are optional.
326
327       The following shell session demonstrates the use of the program:
328
329           $ a.out 3 1 100
330           0.000: timer started
331           3.000: read: 1; total=1
332           4.000: read: 1; total=2
333           ^Z                  # type control-Z to suspend the program
334           [1]+  Stopped                 ./timerfd3_demo 3 1 100
335           $ fg                # Resume execution after a few seconds
336           a.out 3 1 100
337           9.660: read: 5; total=7
338           10.000: read: 1; total=8
339           11.000: read: 1; total=9
340           ^C                  # type control-C to suspend the program
341
342   Program source
343
344       #include <sys/timerfd.h>
345       #include <time.h>
346       #include <unistd.h>
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: %llu; total=%llu\n",
430                       (unsigned long long) exp,
431                       (unsigned long long) tot_exp);
432           }
433
434           exit(EXIT_SUCCESS);
435       }
436

SEE ALSO

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

COLOPHON

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