1TIMERFD_CREATE(2) Linux Programmer's Manual TIMERFD_CREATE(2)
2
3
4
6 timerfd_create, timerfd_settime, timerfd_gettime - timers that notify
7 via file descriptors
8
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 int timerfd_gettime(int fd, struct itimerspec *curr_value);
18
20 These system calls create and operate on a timer that delivers timer
21 expiration notifications via a file descriptor. They provide an alter‐
22 native to the use of setitimer(2) or timer_create(2), with the advan‐
23 tage that the file descriptor may be monitored by select(2), poll(2),
24 and epoll(7).
25
26 The use of these three system calls is analogous to the use of
27 timer_create(2), timer_settime(2), and timer_gettime(2). (There is no
28 analog of timer_getoverrun(2), since that functionality is provided by
29 read(2), as described below.)
30
31 timerfd_create()
32 timerfd_create() creates a new timer object, and returns a file de‐
33 scriptor that refers to that timer. The clockid argument specifies the
34 clock that is used to mark the progress of the timer, and must be one
35 of the following:
36
37 CLOCK_REALTIME
38 A settable system-wide real-time clock.
39
40 CLOCK_MONOTONIC
41 A nonsettable monotonically increasing clock that measures time
42 from some unspecified point in the past that does not change af‐
43 ter system startup.
44
45 CLOCK_BOOTTIME (Since Linux 3.15)
46 Like CLOCK_MONOTONIC, this is a monotonically increasing clock.
47 However, whereas the CLOCK_MONOTONIC clock does not measure the
48 time while a system is suspended, the CLOCK_BOOTTIME clock does
49 include the time during which the system is suspended. This is
50 useful for applications that need to be suspend-aware.
51 CLOCK_REALTIME is not suitable for such applications, since that
52 clock is affected by discontinuous changes to the system clock.
53
54 CLOCK_REALTIME_ALARM (since Linux 3.11)
55 This clock is like CLOCK_REALTIME, but will wake the system if
56 it is suspended. The caller must have the CAP_WAKE_ALARM capa‐
57 bility in order to set a timer against this clock.
58
59 CLOCK_BOOTTIME_ALARM (since Linux 3.11)
60 This clock is like CLOCK_BOOTTIME, but will wake the system if
61 it is suspended. The caller must have the CAP_WAKE_ALARM capa‐
62 bility in order to set a timer against this clock.
63
64 See clock_getres(2) for some further details on the above clocks.
65
66 The current value of each of these clocks can be retrieved using
67 clock_gettime(2).
68
69 Starting with Linux 2.6.27, the following values may be bitwise ORed in
70 flags to change the behavior of timerfd_create():
71
72 TFD_NONBLOCK Set the O_NONBLOCK file status flag on the open file de‐
73 scription (see open(2)) referred to by the new file de‐
74 scriptor. Using this flag saves extra calls to fcntl(2)
75 to achieve the same result.
76
77 TFD_CLOEXEC Set the close-on-exec (FD_CLOEXEC) flag on the new file
78 descriptor. See the description of the O_CLOEXEC flag in
79 open(2) for reasons why this may be useful.
80
81 In Linux versions up to and including 2.6.26, flags must be specified
82 as zero.
83
84 timerfd_settime()
85 timerfd_settime() arms (starts) or disarms (stops) the timer referred
86 to by the file descriptor fd.
87
88 The new_value argument specifies the initial expiration and interval
89 for the timer. The itimerspec structure used for this argument con‐
90 tains two fields, each of which is in turn a structure of type time‐
91 spec:
92
93 struct timespec {
94 time_t tv_sec; /* Seconds */
95 long tv_nsec; /* Nanoseconds */
96 };
97
98 struct itimerspec {
99 struct timespec it_interval; /* Interval for periodic timer */
100 struct timespec it_value; /* Initial expiration */
101 };
102
103 new_value.it_value specifies the initial expiration of the timer, in
104 seconds and nanoseconds. Setting either field of new_value.it_value to
105 a nonzero value arms the timer. Setting both fields of
106 new_value.it_value to zero disarms the timer.
107
108 Setting one or both fields of new_value.it_interval to nonzero values
109 specifies the period, in seconds and nanoseconds, for repeated timer
110 expirations after the initial expiration. If both fields of
111 new_value.it_interval are zero, the timer expires just once, at the
112 time specified by new_value.it_value.
113
114 By default, the initial expiration time specified in new_value is in‐
115 terpreted relative to the current time on the timer's clock at the time
116 of the call (i.e., new_value.it_value specifies a time relative to the
117 current value of the clock specified by clockid). An absolute timeout
118 can be selected via the flags argument.
119
120 The flags argument is a bit mask that can include the following values:
121
122 TFD_TIMER_ABSTIME
123 Interpret new_value.it_value as an absolute value on the timer's
124 clock. The timer will expire when the value of the timer's
125 clock reaches the value specified in new_value.it_value.
126
127 TFD_TIMER_CANCEL_ON_SET
128 If this flag is specified along with TFD_TIMER_ABSTIME and the
129 clock for this timer is CLOCK_REALTIME or CLOCK_REALTIME_ALARM,
130 then mark this timer as cancelable if the real-time clock under‐
131 goes a discontinuous change (settimeofday(2), clock_settime(2),
132 or similar). When such changes occur, a current or future
133 read(2) from the file descriptor will fail with the error ECAN‐
134 CELED.
135
136 If the old_value argument is not NULL, then the itimerspec structure
137 that it points to is used to return the setting of the timer that was
138 current at the time of the call; see the description of timerfd_get‐
139 time() following.
140
141 timerfd_gettime()
142 timerfd_gettime() returns, in curr_value, an itimerspec structure that
143 contains the current setting of the timer referred to by the file de‐
144 scriptor fd.
145
146 The it_value field returns the amount of time until the timer will next
147 expire. If both fields of this structure are zero, then the timer is
148 currently disarmed. This field always contains a relative value, re‐
149 gardless of whether the TFD_TIMER_ABSTIME flag was specified when set‐
150 ting the timer.
151
152 The it_interval field returns the interval of the timer. If both
153 fields of this structure are zero, then the timer is set to expire just
154 once, at the time specified by curr_value.it_value.
155
156 Operating on a timer file descriptor
157 The file descriptor returned by timerfd_create() supports the following
158 additional operations:
159
160 read(2)
161 If the timer has already expired one or more times since its
162 settings were last modified using timerfd_settime(), or since
163 the last successful read(2), then the buffer given to read(2)
164 returns an unsigned 8-byte integer (uint64_t) containing the
165 number of expirations that have occurred. (The returned value
166 is in host byte order—that is, the native byte order for inte‐
167 gers on the host machine.)
168
169 If no timer expirations have occurred at the time of the
170 read(2), then the call either blocks until the next timer expi‐
171 ration, or fails with the error EAGAIN if the file descriptor
172 has been made nonblocking (via the use of the fcntl(2) F_SETFL
173 operation to set the O_NONBLOCK flag).
174
175 A read(2) fails with the error EINVAL if the size of the sup‐
176 plied buffer is less than 8 bytes.
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 specified when calling
181 timerfd_settime(), then read(2) fails with the error ECANCELED
182 if the real-time clock undergoes a discontinuous change. (This
183 allows the reading application to discover such discontinuous
184 changes to the clock.)
185
186 If the associated clock is either CLOCK_REALTIME or CLOCK_REAL‐
187 TIME_ALARM, the timer is absolute (TFD_TIMER_ABSTIME), and the
188 flag TFD_TIMER_CANCEL_ON_SET was not specified when calling
189 timerfd_settime(), then a discontinuous negative change to the
190 clock (e.g., clock_settime(2)) may cause read(2) to unblock, but
191 return a value of 0 (i.e., no bytes read), if the clock change
192 occurs after the time expired, but before the read(2) on the
193 file descriptor.
194
195 poll(2), select(2) (and similar)
196 The file descriptor is readable (the select(2) readfds argument;
197 the poll(2) POLLIN flag) if one or more timer expirations have
198 occurred.
199
200 The file descriptor also supports the other file-descriptor mul‐
201 tiplexing APIs: pselect(2), ppoll(2), and epoll(7).
202
203 ioctl(2)
204 The following timerfd-specific command is supported:
205
206 TFD_IOC_SET_TICKS (since Linux 3.17)
207 Adjust the number of timer expirations that have oc‐
208 curred. The argument is a pointer to a nonzero 8-byte
209 integer (uint64_t*) containing the new number of expira‐
210 tions. Once the number is set, any waiter on the timer
211 is woken up. The only purpose of this command is to re‐
212 store the expirations for the purpose of checkpoint/re‐
213 store. This operation is available only if the kernel
214 was configured with the CONFIG_CHECKPOINT_RESTORE option.
215
216 close(2)
217 When the file descriptor is no longer required it should be
218 closed. When all file descriptors associated with the same
219 timer object have been closed, the timer is disarmed and its re‐
220 sources are freed by the kernel.
221
222 fork(2) semantics
223 After a fork(2), the child inherits a copy of the file descriptor cre‐
224 ated by timerfd_create(). The file descriptor refers to the same un‐
225 derlying timer object as the corresponding file descriptor in the par‐
226 ent, and read(2)s in the child will return information about expira‐
227 tions of the timer.
228
229 execve(2) semantics
230 A file descriptor created by timerfd_create() is preserved across ex‐
231 ecve(2), and continues to generate timer expirations if the timer was
232 armed.
233
235 On success, timerfd_create() returns a new file descriptor. On error,
236 -1 is returned and errno is set to indicate the error.
237
238 timerfd_settime() and timerfd_gettime() return 0 on success; on error
239 they return -1, and set errno to indicate the error.
240
242 timerfd_create() can fail with the following errors:
243
244 EINVAL The clockid is not valid.
245
246 EINVAL flags is invalid; or, in Linux 2.6.26 or earlier, flags is non‐
247 zero.
248
249 EMFILE The per-process limit on the number of open file descriptors has
250 been reached.
251
252 ENFILE The system-wide limit on the total number of open files has been
253 reached.
254
255 ENODEV Could not mount (internal) anonymous inode device.
256
257 ENOMEM There was insufficient kernel memory to create the timer.
258
259 EPERM clockid was CLOCK_REALTIME_ALARM or CLOCK_BOOTTIME_ALARM but the
260 caller did not have the CAP_WAKE_ALARM capability.
261
262 timerfd_settime() and timerfd_gettime() can fail with the following er‐
263 rors:
264
265 EBADF fd is not a valid file descriptor.
266
267 EFAULT new_value, old_value, or curr_value is not valid a pointer.
268
269 EINVAL fd is not a valid timerfd file descriptor.
270
271 timerfd_settime() can also fail with the following errors:
272
273 ECANCELED
274 See NOTES.
275
276 EINVAL new_value is not properly initialized (one of the tv_nsec falls
277 outside the range zero to 999,999,999).
278
279 EINVAL flags is invalid.
280
282 These system calls are available on Linux since kernel 2.6.25. Library
283 support is provided by glibc since version 2.8.
284
286 These system calls are Linux-specific.
287
289 Suppose the following scenario for CLOCK_REALTIME or CLOCK_REAL‐
290 TIME_ALARM timer that was created with timerfd_create():
291
292 (a) The timer has been started (timerfd_settime()) with the
293 TFD_TIMER_ABSTIME and TFD_TIMER_CANCEL_ON_SET flags;
294
295 (b) A discontinuous change (e.g., settimeofday(2)) is subsequently made
296 to the CLOCK_REALTIME clock; and
297
298 (c) the caller once more calls timerfd_settime() to rearm the timer
299 (without first doing a read(2) on the file descriptor).
300
301 In this case the following occurs:
302
303 • The timerfd_settime() returns -1 with errno set to ECANCELED. (This
304 enables the caller to know that the previous timer was affected by a
305 discontinuous change to the clock.)
306
307 • The timer is successfully rearmed with the settings provided in the
308 second timerfd_settime() call. (This was probably an implementation
309 accident, but won't be fixed now, in case there are applications that
310 depend on this behaviour.)
311
313 Currently, timerfd_create() supports fewer types of clock IDs than
314 timer_create(2).
315
317 The following program creates a timer and then monitors its progress.
318 The program accepts up to three command-line arguments. The first ar‐
319 gument specifies the number of seconds for the initial expiration of
320 the timer. The second argument specifies the interval for the timer,
321 in seconds. The third argument specifies the number of times the pro‐
322 gram should allow the timer to expire before terminating. The second
323 and third command-line arguments are optional.
324
325 The following shell session demonstrates the use of the program:
326
327 $ a.out 3 1 100
328 0.000: timer started
329 3.000: read: 1; total=1
330 4.000: read: 1; total=2
331 ^Z # type control-Z to suspend the program
332 [1]+ Stopped ./timerfd3_demo 3 1 100
333 $ fg # Resume execution after a few seconds
334 a.out 3 1 100
335 9.660: read: 5; total=7
336 10.000: read: 1; total=8
337 11.000: read: 1; total=9
338 ^C # type control-C to suspend the program
339
340 Program source
341
342 #include <sys/timerfd.h>
343 #include <time.h>
344 #include <unistd.h>
345 #include <inttypes.h> /* Definition of PRIu64 */
346 #include <stdlib.h>
347 #include <stdio.h>
348 #include <stdint.h> /* Definition of uint64_t */
349
350 #define handle_error(msg) \
351 do { perror(msg); exit(EXIT_FAILURE); } while (0)
352
353 static void
354 print_elapsed_time(void)
355 {
356 static struct timespec start;
357 struct timespec curr;
358 static int first_call = 1;
359 int secs, nsecs;
360
361 if (first_call) {
362 first_call = 0;
363 if (clock_gettime(CLOCK_MONOTONIC, &start) == -1)
364 handle_error("clock_gettime");
365 }
366
367 if (clock_gettime(CLOCK_MONOTONIC, &curr) == -1)
368 handle_error("clock_gettime");
369
370 secs = curr.tv_sec - start.tv_sec;
371 nsecs = curr.tv_nsec - start.tv_nsec;
372 if (nsecs < 0) {
373 secs--;
374 nsecs += 1000000000;
375 }
376 printf("%d.%03d: ", secs, (nsecs + 500000) / 1000000);
377 }
378
379 int
380 main(int argc, char *argv[])
381 {
382 struct itimerspec new_value;
383 int max_exp, fd;
384 struct timespec now;
385 uint64_t exp, tot_exp;
386 ssize_t s;
387
388 if ((argc != 2) && (argc != 4)) {
389 fprintf(stderr, "%s init-secs [interval-secs max-exp]\n",
390 argv[0]);
391 exit(EXIT_FAILURE);
392 }
393
394 if (clock_gettime(CLOCK_REALTIME, &now) == -1)
395 handle_error("clock_gettime");
396
397 /* Create a CLOCK_REALTIME absolute timer with initial
398 expiration and interval as specified in command line. */
399
400 new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
401 new_value.it_value.tv_nsec = now.tv_nsec;
402 if (argc == 2) {
403 new_value.it_interval.tv_sec = 0;
404 max_exp = 1;
405 } else {
406 new_value.it_interval.tv_sec = atoi(argv[2]);
407 max_exp = atoi(argv[3]);
408 }
409 new_value.it_interval.tv_nsec = 0;
410
411 fd = timerfd_create(CLOCK_REALTIME, 0);
412 if (fd == -1)
413 handle_error("timerfd_create");
414
415 if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == -1)
416 handle_error("timerfd_settime");
417
418 print_elapsed_time();
419 printf("timer started\n");
420
421 for (tot_exp = 0; tot_exp < max_exp;) {
422 s = read(fd, &exp, sizeof(uint64_t));
423 if (s != sizeof(uint64_t))
424 handle_error("read");
425
426 tot_exp += exp;
427 print_elapsed_time();
428 printf("read: %" PRIu64 "; total=%" PRIu64 "\n", exp, tot_exp);
429 }
430
431 exit(EXIT_SUCCESS);
432 }
433
435 eventfd(2), poll(2), read(2), select(2), setitimer(2), signalfd(2),
436 timer_create(2), timer_gettime(2), timer_settime(2), epoll(7), time(7)
437
439 This page is part of release 5.12 of the Linux man-pages project. A
440 description of the project, information about reporting bugs, and the
441 latest version of this page, can be found at
442 https://www.kernel.org/doc/man-pages/.
443
444
445
446Linux 2021-03-22 TIMERFD_CREATE(2)