readv2: Note preadv2(..., RWF_NOWAIT) bug in BUGS section
[man-pages.git] / man2 / timerfd_create.2
blob65fdfcc450790b67e57bec526fd0f458f3e74bb4
1 .\" Copyright (C) 2008 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\"
3 .\" %%%LICENSE_START(GPLv2+_SW_3_PARA)
4 .\" This program is free software; you can redistribute it and/or modify
5 .\" it under the terms of the GNU General Public License as published by
6 .\" the Free Software Foundation; either version 2 of the License, or
7 .\" (at your option) any later version.
8 .\"
9 .\" This program is distributed in the hope that it will be useful,
10 .\" but WITHOUT ANY WARRANTY; without even the implied warranty of
11 .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 .\" GNU General Public License for more details.
13 .\"
14 .\" You should have received a copy of the GNU General Public
15 .\" License along with this manual; if not, see
16 .\" <http://www.gnu.org/licenses/>.
17 .\" %%%LICENSE_END
18 .\"
19 .TH TIMERFD_CREATE 2 2021-03-22 Linux "Linux Programmer's Manual"
20 .SH NAME
21 timerfd_create, timerfd_settime, timerfd_gettime \-
22 timers that notify via file descriptors
23 .SH SYNOPSIS
24 .nf
25 .B #include <sys/timerfd.h>
26 .PP
27 .BI "int timerfd_create(int " clockid ", int " flags );
28 .PP
29 .BI "int timerfd_settime(int " fd ", int " flags ,
30 .BI "                    const struct itimerspec *" new_value ,
31 .BI "                    struct itimerspec *" old_value );
32 .BI "int timerfd_gettime(int " fd ", struct itimerspec *" curr_value );
33 .fi
34 .SH DESCRIPTION
35 These system calls create and operate on a timer
36 that delivers timer expiration notifications via a file descriptor.
37 They provide an alternative to the use of
38 .BR setitimer (2)
40 .BR timer_create (2),
41 with the advantage that the file descriptor may be monitored by
42 .BR select (2),
43 .BR poll (2),
44 and
45 .BR epoll (7).
46 .PP
47 The use of these three system calls is analogous to the use of
48 .BR timer_create (2),
49 .BR timer_settime (2),
50 and
51 .BR timer_gettime (2).
52 (There is no analog of
53 .BR timer_getoverrun (2),
54 since that functionality is provided by
55 .BR read (2),
56 as described below.)
57 .\"
58 .SS timerfd_create()
59 .BR timerfd_create ()
60 creates a new timer object,
61 and returns a file descriptor that refers to that timer.
62 The
63 .I clockid
64 argument specifies the clock that is used to mark the progress
65 of the timer, and must be one of the following:
66 .TP
67 .B CLOCK_REALTIME
68 A settable system-wide real-time clock.
69 .TP
70 .B CLOCK_MONOTONIC
71 A nonsettable monotonically increasing clock that measures time
72 from some unspecified point in the past that does not change
73 after system startup.
74 .TP
75 .BR CLOCK_BOOTTIME " (Since Linux 3.15)"
76 .\"    commit 4a2378a943f09907fb1ae35c15de917f60289c14
77 Like
78 .BR CLOCK_MONOTONIC ,
79 this is a monotonically increasing clock.
80 However, whereas the
81 .BR CLOCK_MONOTONIC
82 clock does not measure the time while a system is suspended, the
83 .BR CLOCK_BOOTTIME
84 clock does include the time during which the system is suspended.
85 This is useful for applications that need to be suspend-aware.
86 .BR CLOCK_REALTIME
87 is not suitable for such applications, since that clock is affected
88 by discontinuous changes to the system clock.
89 .TP
90 .BR CLOCK_REALTIME_ALARM " (since Linux 3.11)"
91 .\" commit 11ffa9d6065f344a9bd769a2452f26f2f671e5f8
92 This clock is like
93 .BR CLOCK_REALTIME ,
94 but will wake the system if it is suspended.
95 The caller must have the
96 .B CAP_WAKE_ALARM
97 capability in order to set a timer against this clock.
98 .TP
99 .BR CLOCK_BOOTTIME_ALARM " (since Linux 3.11)"
100 .\" commit 11ffa9d6065f344a9bd769a2452f26f2f671e5f8
101 This clock is like
102 .BR CLOCK_BOOTTIME ,
103 but will wake the system if it is suspended.
104 The caller must have the
105 .B CAP_WAKE_ALARM
106 capability in order to set a timer against this clock.
109 .BR clock_getres (2)
110 for some further details on the above clocks.
112 The current value of each of these clocks can be retrieved using
113 .BR clock_gettime (2).
115 Starting with Linux 2.6.27, the following values may be bitwise ORed in
116 .IR flags
117 to change the behavior of
118 .BR timerfd_create ():
119 .TP 14
120 .B TFD_NONBLOCK
121 Set the
122 .BR O_NONBLOCK
123 file status flag on the open file description (see
124 .BR open (2))
125 referred to by the new file descriptor.
126 Using this flag saves extra calls to
127 .BR fcntl (2)
128 to achieve the same result.
130 .B TFD_CLOEXEC
131 Set the close-on-exec
132 .RB ( FD_CLOEXEC )
133 flag on the new file descriptor.
134 See the description of the
135 .B O_CLOEXEC
136 flag in
137 .BR open (2)
138 for reasons why this may be useful.
140 In Linux versions up to and including 2.6.26,
141 .I flags
142 must be specified as zero.
143 .SS timerfd_settime()
144 .BR timerfd_settime ()
145 arms (starts) or disarms (stops)
146 the timer referred to by the file descriptor
147 .IR fd .
150 .I new_value
151 argument specifies the initial expiration and interval for the timer.
153 .I itimerspec
154 structure used for this argument contains two fields,
155 each of which is in turn a structure of type
156 .IR timespec :
158 .in +4n
160 struct timespec {
161     time_t tv_sec;                /* Seconds */
162     long   tv_nsec;               /* Nanoseconds */
165 struct itimerspec {
166     struct timespec it_interval;  /* Interval for periodic timer */
167     struct timespec it_value;     /* Initial expiration */
172 .I new_value.it_value
173 specifies the initial expiration of the timer,
174 in seconds and nanoseconds.
175 Setting either field of
176 .I new_value.it_value
177 to a nonzero value arms the timer.
178 Setting both fields of
179 .I new_value.it_value
180 to zero disarms the timer.
182 Setting one or both fields of
183 .I new_value.it_interval
184 to nonzero values specifies the period, in seconds and nanoseconds,
185 for repeated timer expirations after the initial expiration.
186 If both fields of
187 .I new_value.it_interval
188 are zero, the timer expires just once, at the time specified by
189 .IR new_value.it_value .
191 By default,
192 the initial expiration time specified in
193 .I new_value
194 is interpreted relative to the current time
195 on the timer's clock at the time of the call (i.e.,
196 .I new_value.it_value
197 specifies a time relative to the current value of the clock specified by
198 .IR clockid ).
199 An absolute timeout can be selected via the
200 .I flags
201 argument.
204 .I flags
205 argument is a bit mask that can include the following values:
207 .B TFD_TIMER_ABSTIME
208 Interpret
209 .I new_value.it_value
210 as an absolute value on the timer's clock.
211 The timer will expire when the value of the timer's
212 clock reaches the value specified in
213 .IR new_value.it_value .
215 .BR TFD_TIMER_CANCEL_ON_SET
216 If this flag is specified along with
217 .B TFD_TIMER_ABSTIME
218 and the clock for this timer is
219 .BR CLOCK_REALTIME
221 .BR CLOCK_REALTIME_ALARM ,
222 then mark this timer as cancelable if the real-time clock
223 undergoes a discontinuous change
224 .RB ( settimeofday (2),
225 .BR clock_settime (2),
226 or similar).
227 When such changes occur, a current or future
228 .BR read (2)
229 from the file descriptor will fail with the error
230 .BR ECANCELED .
232 If the
233 .I old_value
234 argument is not NULL, then the
235 .I itimerspec
236 structure that it points to is used to return the setting of the timer
237 that was current at the time of the call;
238 see the description of
239 .BR timerfd_gettime ()
240 following.
242 .SS timerfd_gettime()
243 .BR timerfd_gettime ()
244 returns, in
245 .IR curr_value ,
247 .IR itimerspec
248 structure that contains the current setting of the timer
249 referred to by the file descriptor
250 .IR fd .
253 .I it_value
254 field returns the amount of time
255 until the timer will next expire.
256 If both fields of this structure are zero,
257 then the timer is currently disarmed.
258 This field always contains a relative value, regardless of whether the
259 .BR TFD_TIMER_ABSTIME
260 flag was specified when setting the timer.
263 .I it_interval
264 field returns the interval of the timer.
265 If both fields of this structure are zero,
266 then the timer is set to expire just once, at the time specified by
267 .IR curr_value.it_value .
268 .SS Operating on a timer file descriptor
269 The file descriptor returned by
270 .BR timerfd_create ()
271 supports the following additional operations:
273 .BR read (2)
274 If the timer has already expired one or more times since
275 its settings were last modified using
276 .BR timerfd_settime (),
277 or since the last successful
278 .BR read (2),
279 then the buffer given to
280 .BR read (2)
281 returns an unsigned 8-byte integer
282 .RI ( uint64_t )
283 containing the number of expirations that have occurred.
284 (The returned value is in host byte order\(emthat is,
285 the native byte order for integers on the host machine.)
287 If no timer expirations have occurred at the time of the
288 .BR read (2),
289 then the call either blocks until the next timer expiration,
290 or fails with the error
291 .B EAGAIN
292 if the file descriptor has been made nonblocking
293 (via the use of the
294 .BR fcntl (2)
295 .B F_SETFL
296 operation to set the
297 .B O_NONBLOCK
298 flag).
301 .BR read (2)
302 fails with the error
303 .B EINVAL
304 if the size of the supplied buffer is less than 8 bytes.
306 If the associated clock is either
307 .BR CLOCK_REALTIME
309 .BR CLOCK_REALTIME_ALARM ,
310 the timer is absolute
311 .RB ( TFD_TIMER_ABSTIME ),
312 and the flag
313 .BR TFD_TIMER_CANCEL_ON_SET
314 was specified when calling
315 .BR timerfd_settime (),
316 then
317 .BR read (2)
318 fails with the error
319 .BR ECANCELED
320 if the real-time clock undergoes a discontinuous change.
321 (This allows the reading application to discover
322 such discontinuous changes to the clock.)
324 If the associated clock is either
325 .BR CLOCK_REALTIME
327 .BR CLOCK_REALTIME_ALARM ,
328 the timer is absolute
329 .RB ( TFD_TIMER_ABSTIME ),
330 and the flag
331 .BR TFD_TIMER_CANCEL_ON_SET
333 .I not
334 specified when calling
335 .BR timerfd_settime (),
336 then a discontinuous negative change to the clock (e.g.,
337 .BR clock_settime (2))
338 may cause
339 .BR read (2)
340 to unblock, but return a value of 0 (i.e., no bytes read),
341 if the clock change occurs after the time expired,
342 but before the
343 .BR read (2)
344 on the file descriptor.
346 .BR poll "(2), " select "(2) (and similar)"
347 The file descriptor is readable
348 (the
349 .BR select (2)
350 .I readfds
351 argument; the
352 .BR poll (2)
353 .B POLLIN
354 flag)
355 if one or more timer expirations have occurred.
357 The file descriptor also supports the other file-descriptor
358 multiplexing APIs:
359 .BR pselect (2),
360 .BR ppoll (2),
362 .BR epoll (7).
364 .BR ioctl (2)
365 The following timerfd-specific command is supported:
368 .BR TFD_IOC_SET_TICKS " (since Linux 3.17)"
369 .\" commit 5442e9fbd7c23172a1c9bc736629cd123a9923f0
370 Adjust the number of timer expirations that have occurred.
371 The argument is a pointer to a nonzero 8-byte integer
372 .RI ( uint64_t *)
373 containing the new number of expirations.
374 Once the number is set, any waiter on the timer is woken up.
375 The only purpose of this command is to restore the expirations
376 for the purpose of checkpoint/restore.
377 This operation is available only if the kernel was configured with the
378 .BR CONFIG_CHECKPOINT_RESTORE
379 option.
382 .BR close (2)
383 When the file descriptor is no longer required it should be closed.
384 When all file descriptors associated with the same timer object
385 have been closed,
386 the timer is disarmed and its resources are freed by the kernel.
388 .SS fork(2) semantics
389 After a
390 .BR fork (2),
391 the child inherits a copy of the file descriptor created by
392 .BR timerfd_create ().
393 The file descriptor refers to the same underlying
394 timer object as the corresponding file descriptor in the parent,
396 .BR read (2)s
397 in the child will return information about
398 expirations of the timer.
400 .SS execve(2) semantics
401 A file descriptor created by
402 .BR timerfd_create ()
403 is preserved across
404 .BR execve (2),
405 and continues to generate timer expirations if the timer was armed.
406 .SH RETURN VALUE
407 On success,
408 .BR timerfd_create ()
409 returns a new file descriptor.
410 On error, \-1 is returned and
411 .I errno
412 is set to indicate the error.
414 .BR timerfd_settime ()
416 .BR timerfd_gettime ()
417 return 0 on success;
418 on error they return \-1, and set
419 .I errno
420 to indicate the error.
421 .SH ERRORS
422 .BR timerfd_create ()
423 can fail with the following errors:
425 .B EINVAL
427 .I clockid
428 is not valid.
430 .B EINVAL
431 .I flags
432 is invalid;
433 or, in Linux 2.6.26 or earlier,
434 .I flags
435 is nonzero.
437 .B EMFILE
438 The per-process limit on the number of open file descriptors has been reached.
440 .B ENFILE
441 The system-wide limit on the total number of open files has been
442 reached.
444 .B ENODEV
445 Could not mount (internal) anonymous inode device.
447 .B ENOMEM
448 There was insufficient kernel memory to create the timer.
450 .B EPERM
451 .I clockid
453 .BR CLOCK_REALTIME_ALARM
455 .BR CLOCK_BOOTTIME_ALARM
456 but the caller did not have the
457 .BR CAP_WAKE_ALARM
458 capability.
460 .BR timerfd_settime ()
462 .BR timerfd_gettime ()
463 can fail with the following errors:
465 .B EBADF
466 .I fd
467 is not a valid file descriptor.
469 .B EFAULT
470 .IR new_value ,
471 .IR old_value ,
473 .I curr_value
474 is not valid a pointer.
476 .B EINVAL
477 .I fd
478 is not a valid timerfd file descriptor.
480 .BR timerfd_settime ()
481 can also fail with the following errors:
483 .B ECANCELED
484 See NOTES.
486 .B EINVAL
487 .I new_value
488 is not properly initialized (one of the
489 .I tv_nsec
490 falls outside the range zero to 999,999,999).
492 .B EINVAL
493 .\" This case only checked since 2.6.29, and 2.2.2[78].some-stable-version.
494 .\" In older kernel versions, no check was made for invalid flags.
495 .I flags
496 is invalid.
497 .SH VERSIONS
498 These system calls are available on Linux since kernel 2.6.25.
499 Library support is provided by glibc since version 2.8.
500 .SH CONFORMING TO
501 These system calls are Linux-specific.
502 .SH NOTES
503 Suppose the following scenario for
504 .BR CLOCK_REALTIME
506 .BR CLOCK_REALTIME_ALARM
507 timer that was created with
508 .BR timerfd_create ():
509 .IP (a) 4
510 The timer has been started
511 .RB ( timerfd_settime ())
512 with the
513 .BR TFD_TIMER_ABSTIME
515 .BR TFD_TIMER_CANCEL_ON_SET
516 flags;
517 .IP (b)
518 A discontinuous change (e.g.,
519 .BR settimeofday (2))
520 is subsequently made to the
521 .BR CLOCK_REALTIME
522 clock; and
523 .IP (c)
524 the caller once more calls
525 .BR timerfd_settime ()
526 to rearm the timer (without first doing a
527 .BR read (2)
528 on the file descriptor).
530 In this case the following occurs:
531 .IP \(bu 2
533 .BR timerfd_settime ()
534 returns \-1 with
535 .I errno
536 set to
537 .BR ECANCELED .
538 (This enables the caller to know that the previous timer was affected
539 by a discontinuous change to the clock.)
540 .IP \(bu
541 The timer
542 .I "is successfully rearmed"
543 with the settings provided in the second
544 .BR timerfd_settime ()
545 call.
546 (This was probably an implementation accident, but won't be fixed now,
547 in case there are applications that depend on this behaviour.)
548 .SH BUGS
549 Currently,
550 .\" 2.6.29
551 .BR timerfd_create ()
552 supports fewer types of clock IDs than
553 .BR timer_create (2).
554 .SH EXAMPLES
555 The following program creates a timer and then monitors its progress.
556 The program accepts up to three command-line arguments.
557 The first argument specifies the number of seconds for
558 the initial expiration of the timer.
559 The second argument specifies the interval for the timer, in seconds.
560 The third argument specifies the number of times the program should
561 allow the timer to expire before terminating.
562 The second and third command-line arguments are optional.
564 The following shell session demonstrates the use of the program:
566 .in +4n
568 .RB "$" " a.out 3 1 100"
569 0.000: timer started
570 3.000: read: 1; total=1
571 4.000: read: 1; total=2
572 .BR "\(haZ " "                 # type control\-Z to suspend the program"
573 [1]+  Stopped                 ./timerfd3_demo 3 1 100
574 .RB "$ " "fg" "                # Resume execution after a few seconds"
575 a.out 3 1 100
576 9.660: read: 5; total=7
577 10.000: read: 1; total=8
578 11.000: read: 1; total=9
579 .BR "\(haC " "                 # type control\-C to suspend the program"
582 .SS Program source
585 .\" The commented out code here is what we currently need until
586 .\" the required stuff is in glibc
589 .\"/* Link with \-lrt */
590 .\"#define _GNU_SOURCE
591 .\"#include <sys/syscall.h>
592 .\"#include <unistd.h>
593 .\"#include <time.h>
594 .\"#if defined(__i386__)
595 .\"#define __NR_timerfd_create 322
596 .\"#define __NR_timerfd_settime 325
597 .\"#define __NR_timerfd_gettime 326
598 .\"#endif
600 .\"static int
601 .\"timerfd_create(int clockid, int flags)
602 .\"{
603 .\"    return syscall(__NR_timerfd_create, clockid, flags);
604 .\"}
606 .\"static int
607 .\"timerfd_settime(int fd, int flags, struct itimerspec *new_value,
608 .\"        struct itimerspec *curr_value)
609 .\"{
610 .\"    return syscall(__NR_timerfd_settime, fd, flags, new_value,
611 .\"                   curr_value);
612 .\"}
614 .\"static int
615 .\"timerfd_gettime(int fd, struct itimerspec *curr_value)
616 .\"{
617 .\"    return syscall(__NR_timerfd_gettime, fd, curr_value);
618 .\"}
620 .\"#define TFD_TIMER_ABSTIME (1 << 0)
622 .\"////////////////////////////////////////////////////////////
623 #include <sys/timerfd.h>
624 #include <time.h>
625 #include <unistd.h>
626 #include <inttypes.h>      /* Definition of PRIu64 */
627 #include <stdlib.h>
628 #include <stdio.h>
629 #include <stdint.h>        /* Definition of uint64_t */
631 #define handle_error(msg) \e
632         do { perror(msg); exit(EXIT_FAILURE); } while (0)
634 static void
635 print_elapsed_time(void)
637     static struct timespec start;
638     struct timespec curr;
639     static int first_call = 1;
640     int secs, nsecs;
642     if (first_call) {
643         first_call = 0;
644         if (clock_gettime(CLOCK_MONOTONIC, &start) == \-1)
645             handle_error("clock_gettime");
646     }
648     if (clock_gettime(CLOCK_MONOTONIC, &curr) == \-1)
649         handle_error("clock_gettime");
651     secs = curr.tv_sec \- start.tv_sec;
652     nsecs = curr.tv_nsec \- start.tv_nsec;
653     if (nsecs < 0) {
654         secs\-\-;
655         nsecs += 1000000000;
656     }
657     printf("%d.%03d: ", secs, (nsecs + 500000) / 1000000);
661 main(int argc, char *argv[])
663     struct itimerspec new_value;
664     int max_exp, fd;
665     struct timespec now;
666     uint64_t exp, tot_exp;
667     ssize_t s;
669     if ((argc != 2) && (argc != 4)) {
670         fprintf(stderr, "%s init\-secs [interval\-secs max\-exp]\en",
671                 argv[0]);
672         exit(EXIT_FAILURE);
673     }
675     if (clock_gettime(CLOCK_REALTIME, &now) == \-1)
676         handle_error("clock_gettime");
678     /* Create a CLOCK_REALTIME absolute timer with initial
679        expiration and interval as specified in command line. */
681     new_value.it_value.tv_sec = now.tv_sec + atoi(argv[1]);
682     new_value.it_value.tv_nsec = now.tv_nsec;
683     if (argc == 2) {
684         new_value.it_interval.tv_sec = 0;
685         max_exp = 1;
686     } else {
687         new_value.it_interval.tv_sec = atoi(argv[2]);
688         max_exp = atoi(argv[3]);
689     }
690     new_value.it_interval.tv_nsec = 0;
692     fd = timerfd_create(CLOCK_REALTIME, 0);
693     if (fd == \-1)
694         handle_error("timerfd_create");
696     if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &new_value, NULL) == \-1)
697         handle_error("timerfd_settime");
699     print_elapsed_time();
700     printf("timer started\en");
702     for (tot_exp = 0; tot_exp < max_exp;) {
703         s = read(fd, &exp, sizeof(uint64_t));
704         if (s != sizeof(uint64_t))
705             handle_error("read");
707         tot_exp += exp;
708         print_elapsed_time();
709         printf("read: %" PRIu64 "; total=%" PRIu64 "\en", exp, tot_exp);
710     }
712     exit(EXIT_SUCCESS);
715 .SH SEE ALSO
716 .BR eventfd (2),
717 .BR poll (2),
718 .BR read (2),
719 .BR select (2),
720 .BR setitimer (2),
721 .BR signalfd (2),
722 .BR timer_create (2),
723 .BR timer_gettime (2),
724 .BR timer_settime (2),
725 .BR epoll (7),
726 .BR time (7)