sigaction.2: Minor tweaks to Peter's patch
[man-pages.git] / man2 / timer_create.2
blob9d353457065a0bb9581422f4b6cd5d6a3033bdba
1 .\" Copyright (c) 2009 Linux Foundation, written by Michael Kerrisk
2 .\"     <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein.  The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .TH TIMER_CREATE 2 2021-03-22 Linux "Linux Programmer's Manual"
27 .SH NAME
28 timer_create \- create a POSIX per-process timer
29 .SH SYNOPSIS
30 .nf
31 .BR "#include <signal.h>" "           /* Definition of " SIGEV_* " constants */"
32 .B  #include <time.h>
33 .PP
34 .BI "int timer_create(clockid_t " clockid ", struct sigevent *restrict " sevp ,
35 .BI "                 timer_t *restrict " timerid );
36 .fi
37 .PP
38 Link with \fI\-lrt\fP.
39 .PP
40 .RS -4
41 Feature Test Macro Requirements for glibc (see
42 .BR feature_test_macros (7)):
43 .RE
44 .PP
45 .BR timer_create ():
46 .nf
47     _POSIX_C_SOURCE >= 199309L
48 .fi
49 .SH DESCRIPTION
50 .BR timer_create ()
51 creates a new per-process interval timer.
52 The ID of the new timer is returned in the buffer pointed to by
53 .IR timerid ,
54 which must be a non-null pointer.
55 This ID is unique within the process, until the timer is deleted.
56 The new timer is initially disarmed.
57 .PP
58 The
59 .I clockid
60 argument specifies the clock that the new timer uses to measure time.
61 It can be specified as one of the following values:
62 .TP
63 .B CLOCK_REALTIME
64 A settable system-wide real-time clock.
65 .TP
66 .B CLOCK_MONOTONIC
67 A nonsettable monotonically increasing clock that measures time
68 from some unspecified point in the past that does not change
69 after system startup.
70 .\" Note: the CLOCK_MONOTONIC_RAW clock added for clock_gettime()
71 .\" in 2.6.28 is not supported for POSIX timers -- mtk, Feb 2009
72 .TP
73 .BR CLOCK_PROCESS_CPUTIME_ID " (since Linux 2.6.12)"
74 A clock that measures (user and system) CPU time consumed by
75 (all of the threads in) the calling process.
76 .TP
77 .BR CLOCK_THREAD_CPUTIME_ID " (since Linux 2.6.12)"
78 A clock that measures (user and system) CPU time consumed by
79 the calling thread.
80 .\" The CLOCK_MONOTONIC_RAW that was added in 2.6.28 can't be used
81 .\" to create a timer -- mtk, Feb 2009
82 .TP
83 .BR CLOCK_BOOTTIME " (Since Linux 2.6.39)"
84 .\" commit 70a08cca1227dc31c784ec930099a4417a06e7d0
85 Like
86 .BR CLOCK_MONOTONIC ,
87 this is a monotonically increasing clock.
88 However, whereas the
89 .BR CLOCK_MONOTONIC
90 clock does not measure the time while a system is suspended, the
91 .BR CLOCK_BOOTTIME
92 clock does include the time during which the system is suspended.
93 This is useful for applications that need to be suspend-aware.
94 .BR CLOCK_REALTIME
95 is not suitable for such applications, since that clock is affected
96 by discontinuous changes to the system clock.
97 .TP
98 .BR CLOCK_REALTIME_ALARM " (since Linux 3.0)"
99 .\" commit 9a7adcf5c6dea63d2e47e6f6d2f7a6c9f48b9337
100 This clock is like
101 .BR CLOCK_REALTIME ,
102 but will wake the system if it is suspended.
103 The caller must have the
104 .B CAP_WAKE_ALARM
105 capability in order to set a timer against this clock.
107 .BR CLOCK_BOOTTIME_ALARM " (since Linux 3.0)"
108 .\" commit 9a7adcf5c6dea63d2e47e6f6d2f7a6c9f48b9337
109 This clock is like
110 .BR CLOCK_BOOTTIME ,
111 but will wake the system if it is suspended.
112 The caller must have the
113 .B CAP_WAKE_ALARM
114 capability in order to set a timer against this clock.
116 .BR CLOCK_TAI " (since Linux 3.10)"
117 A system-wide clock derived from wall-clock time but ignoring leap seconds.
120 .BR clock_getres (2)
121 for some further details on the above clocks.
123 As well as the above values,
124 .I clockid
125 can be specified as the
126 .I clockid
127 returned by a call to
128 .BR clock_getcpuclockid (3)
130 .BR pthread_getcpuclockid (3).
133 .I sevp
134 argument points to a
135 .I sigevent
136 structure that specifies how the caller
137 should be notified when the timer expires.
138 For the definition and general details of this structure, see
139 .BR sigevent (7).
142 .I sevp.sigev_notify
143 field can have the following values:
145 .BR SIGEV_NONE
146 Don't asynchronously notify when the timer expires.
147 Progress of the timer can be monitored using
148 .BR timer_gettime (2).
150 .BR SIGEV_SIGNAL
151 Upon timer expiration, generate the signal
152 .I sigev_signo
153 for the process.
155 .BR sigevent (7)
156 for general details.
158 .I si_code
159 field of the
160 .I siginfo_t
161 structure will be set to
162 .BR SI_TIMER .
163 At any point in time,
164 at most one signal is queued to the process for a given timer; see
165 .BR timer_getoverrun (2)
166 for more details.
168 .BR SIGEV_THREAD
169 Upon timer expiration, invoke
170 .I sigev_notify_function
171 as if it were the start function of a new thread.
173 .BR sigevent (7)
174 for details.
176 .BR SIGEV_THREAD_ID " (Linux-specific)"
177 As for
178 .BR SIGEV_SIGNAL ,
179 but the signal is targeted at the thread whose ID is given in
180 .IR sigev_notify_thread_id ,
181 which must be a thread in the same process as the caller.
183 .IR sigev_notify_thread_id
184 field specifies a kernel thread ID, that is, the value returned by
185 .BR clone (2)
187 .BR gettid (2).
188 This flag is intended only for use by threading libraries.
190 Specifying
191 .I sevp
192 as NULL is equivalent to specifying a pointer to a
193 .I sigevent
194 structure in which
195 .I sigev_notify
197 .BR SIGEV_SIGNAL ,
198 .I sigev_signo
200 .BR SIGALRM ,
202 .I sigev_value.sival_int
203 is the timer ID.
204 .SH RETURN VALUE
205 On success,
206 .BR timer_create ()
207 returns 0, and the ID of the new timer is placed in
208 .IR *timerid .
209 On failure, \-1 is returned, and
210 .I errno
211 is set to indicate the error.
212 .SH ERRORS
214 .B EAGAIN
215 Temporary error during kernel allocation of timer structures.
217 .B EINVAL
218 Clock ID,
219 .IR sigev_notify ,
220 .IR sigev_signo ,
222 .IR sigev_notify_thread_id
223 is invalid.
225 .B ENOMEM
226 .\" glibc layer: malloc()
227 Could not allocate memory.
229 .B ENOTSUP
230 The kernel does not support creating a timer against this
231 .IR clockid .
233 .B EPERM
234 .I clockid
236 .BR CLOCK_REALTIME_ALARM
238 .BR CLOCK_BOOTTIME_ALARM
239 but the caller did not have the
240 .BR CAP_WAKE_ALARM
241 capability.
242 .SH VERSIONS
243 This system call is available since Linux 2.6.
244 .SH CONFORMING TO
245 POSIX.1-2001, POSIX.1-2008.
246 .SH NOTES
247 A program may create multiple interval timers using
248 .BR timer_create ().
250 Timers are not inherited by the child of a
251 .BR fork (2),
252 and are disarmed and deleted during an
253 .BR execve (2).
255 The kernel preallocates a "queued real-time signal"
256 for each timer created using
257 .BR timer_create ().
258 Consequently, the number of timers is limited by the
259 .BR RLIMIT_SIGPENDING
260 resource limit (see
261 .BR setrlimit (2)).
263 The timers created by
264 .BR timer_create ()
265 are commonly known as "POSIX (interval) timers".
266 The POSIX timers API consists of the following interfaces:
267 .IP * 3
268 .BR timer_create ():
269 Create a timer.
270 .IP *
271 .BR timer_settime (2):
272 Arm (start) or disarm (stop) a timer.
273 .IP *
274 .BR timer_gettime (2):
275 Fetch the time remaining until the next expiration of a timer,
276 along with the interval setting of the timer.
277 .IP *
278 .BR timer_getoverrun (2):
279 Return the overrun count for the last timer expiration.
280 .IP *
281 .BR timer_delete (2):
282 Disarm and delete a timer.
284 Since Linux 3.10, the
285 .IR /proc/[pid]/timers
286 file can be used to list the POSIX timers for the process with PID
287 .IR pid .
289 .BR proc (5)
290 for further information.
292 Since Linux 4.10,
293 .\" baa73d9e478ff32d62f3f9422822b59dd9a95a21
294 support for POSIX timers is a configurable option that is enabled by default.
295 Kernel support can be disabled via the
296 .BR CONFIG_POSIX_TIMERS
297 option.
299 .SS C library/kernel differences
300 Part of the implementation of the POSIX timers API is provided by glibc.
301 .\" See nptl/sysdeps/unix/sysv/linux/timer_create.c
302 In particular:
303 .IP * 3
304 Much of the functionality for
305 .BR SIGEV_THREAD
306 is implemented within glibc, rather than the kernel.
307 (This is necessarily so,
308 since the thread involved in handling the notification is one
309 that must be managed by the C library POSIX threads implementation.)
310 Although the notification delivered to the process is via a thread,
311 internally the NPTL implementation uses a
312 .I sigev_notify
313 value of
314 .BR SIGEV_THREAD_ID
315 along with a real-time signal that is reserved by the implementation (see
316 .BR nptl (7)).
317 .IP *
318 The implementation of the default case where
319 .I evp
320 is NULL is handled inside glibc,
321 which invokes the underlying system call with a suitably populated
322 .I sigevent
323 structure.
324 .IP *
325 The timer IDs presented at user level are maintained by glibc,
326 which maps these IDs to the timer IDs employed by the kernel.
327 .\" See the glibc source file kernel-posix-timers.h for the structure
328 .\" that glibc uses to map user-space timer IDs to kernel timer IDs
329 .\" The kernel-level timer ID is exposed via siginfo.si_tid.
331 The POSIX timers system calls first appeared in Linux 2.6.
332 Prior to this,
333 glibc provided an incomplete user-space implementation
334 .RB ( CLOCK_REALTIME
335 timers only) using POSIX threads,
336 and in glibc versions before 2.17,
337 .\" glibc commit 93a78ac437ba44f493333d7e2a4b0249839ce460
338 the implementation falls back to this technique on systems
339 running pre-2.6 Linux kernels.
340 .SH EXAMPLES
341 The program below takes two arguments: a sleep period in seconds,
342 and a timer frequency in nanoseconds.
343 The program establishes a handler for the signal it uses for the timer,
344 blocks that signal,
345 creates and arms a timer that expires with the given frequency,
346 sleeps for the specified number of seconds,
347 and then unblocks the timer signal.
348 Assuming that the timer expired at least once while the program slept,
349 the signal handler will be invoked,
350 and the handler displays some information about the timer notification.
351 The program terminates after one invocation of the signal handler.
353 In the following example run, the program sleeps for 1 second,
354 after creating a timer that has a frequency of 100 nanoseconds.
355 By the time the signal is unblocked and delivered,
356 there have been around ten million overruns.
358 .in +4n
360 $ \fB./a.out 1 100\fP
361 Establishing handler for signal 34
362 Blocking signal 34
363 timer ID is 0x804c008
364 Sleeping for 1 seconds
365 Unblocking signal 34
366 Caught signal 34
367     sival_ptr = 0xbfb174f4;     *sival_ptr = 0x804c008
368     overrun count = 10004886
371 .SS Program source
374 #include <stdint.h>
375 #include <stdlib.h>
376 #include <unistd.h>
377 #include <stdio.h>
378 #include <signal.h>
379 #include <time.h>
381 #define CLOCKID CLOCK_REALTIME
382 #define SIG SIGRTMIN
384 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
385                         } while (0)
387 static void
388 print_siginfo(siginfo_t *si)
390     timer_t *tidp;
391     int or;
393     tidp = si\->si_value.sival_ptr;
395     printf("    sival_ptr = %p; ", si\->si_value.sival_ptr);
396     printf("    *sival_ptr = %#jx\en", (uintmax_t) *tidp);
398     or = timer_getoverrun(*tidp);
399     if (or == \-1)
400         errExit("timer_getoverrun");
401     else
402         printf("    overrun count = %d\en", or);
405 static void
406 handler(int sig, siginfo_t *si, void *uc)
408     /* Note: calling printf() from a signal handler is not safe
409        (and should not be done in production programs), since
410        printf() is not async\-signal\-safe; see signal\-safety(7).
411        Nevertheless, we use printf() here as a simple way of
412        showing that the handler was called. */
414     printf("Caught signal %d\en", sig);
415     print_siginfo(si);
416     signal(sig, SIG_IGN);
420 main(int argc, char *argv[])
422     timer_t timerid;
423     struct sigevent sev;
424     struct itimerspec its;
425     long long freq_nanosecs;
426     sigset_t mask;
427     struct sigaction sa;
429     if (argc != 3) {
430         fprintf(stderr, "Usage: %s <sleep\-secs> <freq\-nanosecs>\en",
431                 argv[0]);
432         exit(EXIT_FAILURE);
433     }
435     /* Establish handler for timer signal. */
437     printf("Establishing handler for signal %d\en", SIG);
438     sa.sa_flags = SA_SIGINFO;
439     sa.sa_sigaction = handler;
440     sigemptyset(&sa.sa_mask);
441     if (sigaction(SIG, &sa, NULL) == \-1)
442         errExit("sigaction");
444     /* Block timer signal temporarily. */
446     printf("Blocking signal %d\en", SIG);
447     sigemptyset(&mask);
448     sigaddset(&mask, SIG);
449     if (sigprocmask(SIG_SETMASK, &mask, NULL) == \-1)
450         errExit("sigprocmask");
452     /* Create the timer. */
454     sev.sigev_notify = SIGEV_SIGNAL;
455     sev.sigev_signo = SIG;
456     sev.sigev_value.sival_ptr = &timerid;
457     if (timer_create(CLOCKID, &sev, &timerid) == \-1)
458         errExit("timer_create");
460     printf("timer ID is %#jx\en", (uintmax_t) timerid);
462     /* Start the timer. */
464     freq_nanosecs = atoll(argv[2]);
465     its.it_value.tv_sec = freq_nanosecs / 1000000000;
466     its.it_value.tv_nsec = freq_nanosecs % 1000000000;
467     its.it_interval.tv_sec = its.it_value.tv_sec;
468     its.it_interval.tv_nsec = its.it_value.tv_nsec;
470     if (timer_settime(timerid, 0, &its, NULL) == \-1)
471          errExit("timer_settime");
473     /* Sleep for a while; meanwhile, the timer may expire
474        multiple times. */
476     printf("Sleeping for %d seconds\en", atoi(argv[1]));
477     sleep(atoi(argv[1]));
479     /* Unlock the timer signal, so that timer notification
480        can be delivered. */
482     printf("Unblocking signal %d\en", SIG);
483     if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == \-1)
484         errExit("sigprocmask");
486     exit(EXIT_SUCCESS);
489 .SH SEE ALSO
490 .ad l
492 .BR clock_gettime (2),
493 .BR setitimer (2),
494 .BR timer_delete (2),
495 .BR timer_getoverrun (2),
496 .BR timer_settime (2),
497 .BR timerfd_create (2),
498 .BR clock_getcpuclockid (3),
499 .BR pthread_getcpuclockid (3),
500 .BR pthreads (7),
501 .BR sigevent (7),
502 .BR signal (7),
503 .BR time (7)