1timerfd_create(2)             System Calls Manual            timerfd_create(2)
2
3
4

NAME

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

LIBRARY

10       Standard C library (libc, -lc)
11

SYNOPSIS

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

DESCRIPTION

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

RETURN VALUE

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

ERRORS

234       timerfd_create() can fail with the following errors:
235
236       EINVAL The clockid is not valid.
237
238       EINVAL flags  is invalid; or, in Linux 2.6.26 or earlier, flags is non‐
239              zero.
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       EPERM  clockid was CLOCK_REALTIME_ALARM or CLOCK_BOOTTIME_ALARM but the
252              caller did not have the CAP_WAKE_ALARM capability.
253
254       timerfd_settime() and timerfd_gettime() can fail with the following er‐
255       rors:
256
257       EBADF  fd is not a valid file descriptor.
258
259       EFAULT new_value, old_value, or curr_value is not a valid pointer.
260
261       EINVAL fd is not a valid timerfd file descriptor.
262
263       timerfd_settime() can also fail with the following errors:
264
265       ECANCELED
266              See NOTES.
267
268       EINVAL new_value is not properly initialized (one of the tv_nsec  falls
269              outside the range zero to 999,999,999).
270
271       EINVAL flags is invalid.
272

STANDARDS

274       Linux.
275

HISTORY

277       Linux 2.6.25, glibc 2.8.
278

NOTES

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

BUGS

304       Currently, timerfd_create() supports fewer  types  of  clock  IDs  than
305       timer_create(2).
306

EXAMPLES

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

SEE ALSO

423       eventfd(2),  poll(2),  read(2),  select(2),  setitimer(2), signalfd(2),
424       timer_create(2),   timer_gettime(2),   timer_settime(2),   timespec(3),
425       epoll(7), time(7)
426
427
428
429Linux man-pages 6.05              2023-05-03                 timerfd_create(2)
Impressum