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       The current value of each  of  these  clocks  can  be  retrieved  using
66       clock_gettime(2).
67
68       Starting with Linux 2.6.27, the following values may be bitwise ORed in
69       flags to change the behavior of timerfd_create():
70
71       TFD_NONBLOCK  Set the O_NONBLOCK file status  flag  on  the  open  file
72                     description  (see  open(2))  referred  to by the new file
73                     descriptor.   Using  this  flag  saves  extra  calls   to
74                     fcntl(2) to achieve the same result.
75
76       TFD_CLOEXEC   Set  the  close-on-exec (FD_CLOEXEC) flag on the new file
77                     descriptor.  See the description of the O_CLOEXEC flag in
78                     open(2) for reasons why this may be useful.
79
80       In  Linux  versions up to and including 2.6.26, flags must be specified
81       as zero.
82
83   timerfd_settime()
84       timerfd_settime() arms (starts) or disarms (stops) the  timer  referred
85       to by the file descriptor fd.
86
87       The  new_value  argument  specifies the initial expiration and interval
88       for the timer.  The itimerspec structure used for  this  argument  con‐
89       tains  two  fields,  each of which is in turn a structure of type time‐
90       spec:
91
92           struct timespec {
93               time_t tv_sec;                /* Seconds */
94               long   tv_nsec;               /* Nanoseconds */
95           };
96
97           struct itimerspec {
98               struct timespec it_interval;  /* Interval for periodic timer */
99               struct timespec it_value;     /* Initial expiration */
100           };
101
102       new_value.it_value specifies the initial expiration of  the  timer,  in
103       seconds and nanoseconds.  Setting either field of new_value.it_value to
104       a  nonzero  value   arms   the   timer.    Setting   both   fields   of
105       new_value.it_value to zero disarms the timer.
106
107       Setting  one  or both fields of new_value.it_interval to nonzero values
108       specifies the period, in seconds and nanoseconds,  for  repeated  timer
109       expirations   after   the   initial  expiration.   If  both  fields  of
110       new_value.it_interval are zero, the timer expires  just  once,  at  the
111       time specified by new_value.it_value.
112
113       By  default,  the  initial  expiration  time  specified in new_value is
114       interpreted relative to the current time on the timer's  clock  at  the
115       time of the call (i.e., new_value.it_value specifies a time relative to
116       the current value of the clock  specified  by  clockid).   An  absolute
117       timeout can be selected via the flags argument.
118
119       The flags argument is a bit mask that can include the following values:
120
121       TFD_TIMER_ABSTIME
122              Interpret new_value.it_value as an absolute value on the timer's
123              clock.  The timer will expire when  the  value  of  the  timer's
124              clock reaches the value specified in new_value.it_value.
125
126       TFD_TIMER_CANCEL_ON_SET
127              If  this  flag is specified along with TFD_TIMER_ABSTIME and the
128              clock for this timer is CLOCK_REALTIME or  CLOCK_REALTIME_ALARM,
129              then mark this timer as cancelable if the real-time clock under‐
130              goes a discontinuous change (settimeofday(2),  clock_settime(2),
131              or  similar).   When  such  changes  occur,  a current or future
132              read(2) from the file descriptor will fail with the error  ECAN‐
133              CELED.
134
135       If  the  old_value  argument is not NULL, then the itimerspec structure
136       that it points to is used to return the setting of the timer  that  was
137       current  at  the  time of the call; see the description of timerfd_get‐
138       time() following.
139
140   timerfd_gettime()
141       timerfd_gettime() returns, in curr_value, an itimerspec structure  that
142       contains  the  current  setting  of  the  timer referred to by the file
143       descriptor fd.
144
145       The it_value field returns the amount of time until the timer will next
146       expire.   If  both fields of this structure are zero, then the timer is
147       currently disarmed.  This  field  always  contains  a  relative  value,
148       regardless  of  whether  the  TFD_TIMER_ABSTIME flag was specified when
149       setting the timer.
150
151       The it_interval field returns the  interval  of  the  timer.   If  both
152       fields of this structure are zero, then the timer is set to expire just
153       once, at the time specified by curr_value.it_value.
154
155   Operating on a timer file descriptor
156       The file descriptor returned by timerfd_create() supports the following
157       operations:
158
159       read(2)
160              If  the  timer  has  already expired one or more times since its
161              settings were last modified using  timerfd_settime(),  or  since
162              the  last  successful  read(2), then the buffer given to read(2)
163              returns an unsigned 8-byte  integer  (uint64_t)  containing  the
164              number  of  expirations that have occurred.  (The returned value
165              is in host byte order—that is, the native byte order  for  inte‐
166              gers on the host machine.)
167
168              If  no  timer  expirations  have  occurred  at  the  time of the
169              read(2), then the call either blocks until the next timer  expi‐
170              ration,  or  fails  with the error EAGAIN if the file descriptor
171              has been made nonblocking (via the use of the  fcntl(2)  F_SETFL
172              operation to set the O_NONBLOCK flag).
173
174              A  read(2)  fails  with the error EINVAL if the size of the sup‐
175              plied buffer is less than 8 bytes.
176
177              If the associated clock is either CLOCK_REALTIME or  CLOCK_REAL‐
178              TIME_ALARM,  the  timer is absolute (TFD_TIMER_ABSTIME), and the
179              flag  TFD_TIMER_CANCEL_ON_SET   was   specified   when   calling
180              timerfd_settime(),  then  read(2) fails with the error ECANCELED
181              if the real-time clock undergoes a discontinuous change.   (This
182              allows  the  reading  application to discover such discontinuous
183              changes to the clock.)
184
185       poll(2), select(2) (and similar)
186              The file descriptor is readable (the select(2) readfds argument;
187              the  poll(2)  POLLIN flag) if one or more timer expirations have
188              occurred.
189
190              The file descriptor also supports the other file-descriptor mul‐
191              tiplexing APIs: pselect(2), ppoll(2), and epoll(7).
192
193       ioctl(2)
194              The following timerfd-specific command is supported:
195
196              TFD_IOC_SET_TICKS (since Linux 3.17)
197                     Adjust   the   number  of  timer  expirations  that  have
198                     occurred.  The argument is a pointer to a nonzero  8-byte
199                     integer  (uint64_t*) containing the new number of expira‐
200                     tions.  Once the number is set, any waiter on  the  timer
201                     is  woken  up.   The  only  purpose of this command is to
202                     restore  the  expirations  for  the  purpose  of   check‐
203                     point/restore.   This  operation is available only if the
204                     kernel was configured with the  CONFIG_CHECKPOINT_RESTORE
205                     option.
206
207       close(2)
208              When  the  file  descriptor  is  no longer required it should be
209              closed.  When all file  descriptors  associated  with  the  same
210              timer  object  have  been  closed, the timer is disarmed and its
211              resources are freed by the kernel.
212
213   fork(2) semantics
214       After a fork(2), the child inherits a copy of the file descriptor  cre‐
215       ated  by  timerfd_create().   The  file  descriptor  refers to the same
216       underlying timer object as the corresponding  file  descriptor  in  the
217       parent, and read(2)s in the child will return information about expira‐
218       tions of the timer.
219
220   execve(2) semantics
221       A file descriptor  created  by  timerfd_create()  is  preserved  across
222       execve(2), and continues to generate timer expirations if the timer was
223       armed.
224

RETURN VALUE

226       On success, timerfd_create() returns a new file descriptor.  On  error,
227       -1 is returned and errno is set to indicate the error.
228
229       timerfd_settime()  and  timerfd_gettime() return 0 on success; on error
230       they return -1, and set errno to indicate the error.
231

ERRORS

233       timerfd_create() can fail with the following errors:
234
235       EINVAL The clockid argument is neither CLOCK_MONOTONIC nor  CLOCK_REAL‐
236              TIME;
237
238       EINVAL flags  is  invalid;  or,  in  Linux  2.6.26 or earlier, flags is
239              nonzero.
240
241       EMFILE The per-process limit on the number of open file descriptors has
242              been reached.
243
244       ENFILE The system-wide limit on the total number of open files has been
245              reached.
246
247       ENODEV Could not mount (internal) anonymous inode device.
248
249       ENOMEM There was insufficient kernel memory to create the timer.
250
251       timerfd_settime() and timerfd_gettime() can  fail  with  the  following
252       errors:
253
254       EBADF  fd is not a valid file descriptor.
255
256       EFAULT new_value, old_value, or curr_value is not valid a pointer.
257
258       EINVAL fd is not a valid timerfd file descriptor.
259
260       timerfd_settime() can also fail with the following errors:
261
262       EINVAL new_value  is not properly initialized (one of the tv_nsec falls
263              outside the range zero to 999,999,999).
264
265       EINVAL flags is invalid.
266

VERSIONS

268       These system calls are available on Linux since kernel 2.6.25.  Library
269       support is provided by glibc since version 2.8.
270

CONFORMING TO

272       These system calls are Linux-specific.
273

BUGS

275       Currently,  timerfd_create()  supports  fewer  types  of clock IDs than
276       timer_create(2).
277

EXAMPLE

279       The following program creates a timer and then monitors  its  progress.
280       The  program  accepts  up  to  three command-line arguments.  The first
281       argument specifies the number of seconds for the initial expiration  of
282       the  timer.   The second argument specifies the interval for the timer,
283       in seconds.  The third argument specifies the number of times the  pro‐
284       gram  should  allow the timer to expire before terminating.  The second
285       and third command-line arguments are optional.
286
287       The following shell session demonstrates the use of the program:
288
289           $ a.out 3 1 100
290           0.000: timer started
291           3.000: read: 1; total=1
292           4.000: read: 1; total=2
293           ^Z                  # type control-Z to suspend the program
294           [1]+  Stopped                 ./timerfd3_demo 3 1 100
295           $ fg                # Resume execution after a few seconds
296           a.out 3 1 100
297           9.660: read: 5; total=7
298           10.000: read: 1; total=8
299           11.000: read: 1; total=9
300           ^C                  # type control-C to suspend the program
301
302   Program source
303
304       #include <sys/timerfd.h>
305       #include <time.h>
306       #include <unistd.h>
307       #include <stdlib.h>
308       #include <stdio.h>
309       #include <stdint.h>        /* Definition of uint64_t */
310
311       #define handle_error(msg) \
312               do { perror(msg); exit(EXIT_FAILURE); } while (0)
313
314       static void
315       print_elapsed_time(void)
316       {
317           static struct timespec start;
318           struct timespec curr;
319           static int first_call = 1;
320           int secs, nsecs;
321
322           if (first_call) {
323               first_call = 0;
324               if (clock_gettime(CLOCK_MONOTONIC, &start) == -1)
325                   handle_error("clock_gettime");
326           }
327
328           if (clock_gettime(CLOCK_MONOTONIC, &curr) == -1)
329               handle_error("clock_gettime");
330
331           secs = curr.tv_sec - start.tv_sec;
332           nsecs = curr.tv_nsec - start.tv_nsec;
333           if (nsecs < 0) {
334               secs--;
335               nsecs += 1000000000;
336           }
337           printf("%d.%03d: ", secs, (nsecs + 500000) / 1000000);
338       }
339
340       int
341       main(int argc, char *argv[])
342       {
343           struct itimerspec new_value;
344           int max_exp, fd;
345           struct timespec now;
346           uint64_t exp, tot_exp;
347           ssize_t s;
348
349           if ((argc != 2) && (argc != 4)) {
350               fprintf(stderr, "%s init-secs [interval-secs max-exp]\n",
351                       argv[0]);
352               exit(EXIT_FAILURE);
353           }
354
355           if (clock_gettime(CLOCK_REALTIME, &now) == -1)
356               handle_error("clock_gettime");
357
358           /* Create a CLOCK_REALTIME absolute timer with initial
359              expiration and interval as specified in command line */
360
361           new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
362           new_value.it_value.tv_nsec = now.tv_nsec;
363           if (argc == 2) {
364               new_value.it_interval.tv_sec = 0;
365               max_exp = 1;
366           } else {
367               new_value.it_interval.tv_sec = atoi(argv[2]);
368               max_exp = atoi(argv[3]);
369           }
370           new_value.it_interval.tv_nsec = 0;
371
372           fd = timerfd_create(CLOCK_REALTIME, 0);
373           if (fd == -1)
374               handle_error("timerfd_create");
375
376           if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
377               handle_error("timerfd_settime");
378
379           print_elapsed_time();
380           printf("timer started\n");
381
382           for (tot_exp = 0; tot_exp < max_exp;) {
383               s = read(fd, &exp, sizeof(uint64_t));
384               if (s != sizeof(uint64_t))
385                   handle_error("read");
386
387               tot_exp += exp;
388               print_elapsed_time();
389               printf("read: %llu; total=%llu\n",
390                       (unsigned long long) exp,
391                       (unsigned long long) tot_exp);
392           }
393
394           exit(EXIT_SUCCESS);
395       }
396

SEE ALSO

398       eventfd(2), poll(2),  read(2),  select(2),  setitimer(2),  signalfd(2),
399       timer_create(2), timer_gettime(2), timer_settime(2), epoll(7), time(7)
400

COLOPHON

402       This  page  is  part of release 5.02 of the Linux man-pages project.  A
403       description of the project, information about reporting bugs,  and  the
404       latest     version     of     this    page,    can    be    found    at
405       https://www.kernel.org/doc/man-pages/.
406
407
408
409Linux                             2019-03-06                 TIMERFD_CREATE(2)
Impressum