timer_create(2)

โœจ timer_create(2) โœจ โ€” the timer_create system call, bestie

okay so real talk, this is part of section 2 (the system calls manual) and it's giving "let's build a timer" energy ๐Ÿ’–


๐ŸŽ€ NAME ๐ŸŽ€

timer_create โ€” create a POSIX per-process timer

๐Ÿ“š LIBRARY ๐Ÿ“š

Real-time library (librt, -lrt) โ€” yeah you gotta link it, don't forget ๐Ÿ’…

๐ŸŒธ SYNOPSIS ๐ŸŒธ

#include <signal.h>           /* Definition of SIGEV_* constants */
#include <time.h>

int timer_create(clockid_t clockid,
                 struct sigevent *_Nullable restrict sevp,
                 timer_t *restrict timerid);

Feature Test Macro Requirements for glibc (go peek at feature_test_macros(7) if you're lost):

timer_create():
    _POSIX_C_SOURCE >= 199309L

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

timer_create() creates a brand new per-process interval timer, no cap. The ID of your shiny new timer comes back in the buffer pointed to by timerid, which must be a non-null pointer (so like, actually give it somewhere to live, bestie ๐Ÿ™ˆ). This ID is unique within the process until you delete the timer. And the new timer? Initially disarmed. It's just chillin. Not doing anything yet. You gotta arm it later.

The clockid argument says which clock your new timer uses to measure time. It's one of these:

  • CLOCK_REALTIME โ€” a settable system-wide real-time clock. yes, the one that can get yeeted around by the admin.
  • CLOCK_MONOTONIC โ€” a nonsettable, monotonically increasing clock. It measures time from some unspecified point in the past, and that reference point does not change after system startup. Iconic, stable, reliable.
  • CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12) โ€” measures the (user and system) CPU time consumed by (all of the threads in) the calling process.
  • CLOCK_THREAD_CPUTIME_ID (since Linux 2.6.12) โ€” measures the (user and system) CPU time consumed by the calling thread. just the one thread, main character only ๐Ÿ’…
  • CLOCK_BOOTTIME (since Linux 2.6.39) โ€” like CLOCK_MONOTONIC, it's monotonically increasing. BUT here's the tea: CLOCK_MONOTONIC does NOT count time while the system is suspended, whereas CLOCK_BOOTTIME does include the time the system spent suspended. So if your app needs to be suspend-aware, this is the one. CLOCK_REALTIME is not it for those apps, because that clock gets affected by discontinuous changes to the system clock. ๐Ÿ˜ญ
  • CLOCK_REALTIME_ALARM (since Linux 3.0) โ€” like CLOCK_REALTIME, but it will wake the system if it's suspended. The caller must have the CAP_WAKE_ALARM capability to set a timer against this clock. no cap, no wake-up fr fr.
  • CLOCK_BOOTTIME_ALARM (since Linux 3.0) โ€” like CLOCK_BOOTTIME, but it will wake the system if it's suspended. Same deal: the caller must have the CAP_WAKE_ALARM capability to set a timer against this clock.
  • CLOCK_TAI (since Linux 3.10) โ€” a system-wide clock derived from wall-clock time but counting leap seconds. yes leap seconds, she's fancy โœจ

Want even more details on all these clocks? Go read clock_getres(2), it's right there.

And plot twist: on top of all those values, clockid can also be the clockid returned by a call to clock_getcpuclockid(3) or pthread_getcpuclockid(3). versatile queen ๐Ÿ‘‘

The sevp argument points to a sigevent structure that says how the caller should be notified when the timer expires. For the definition and the general deets on that struct, see sigevent(3type).

The sevp.sigev_notify field can be any of these:

  • SIGEV_NONE โ€” don't asynchronously notify when the timer expires. You can still watch the timer's progress yourself using timer_gettime(2).
  • SIGEV_SIGNAL โ€” when the timer expires, generate the signal sigev_signo for the process. See sigevent(3type) for general details. The si_code field of the siginfo_t structure gets set to SI_TIMER. And heads up: at any point in time, at most one signal is queued to the process for a given timer โ€” see timer_getoverrun(2) for the full story.
  • SIGEV_THREAD โ€” when the timer expires, invoke sigev_notify_function as if it were the start function of a new thread. See sigevent(3type) for details.
  • SIGEV_THREAD_ID (Linux-specific ๐Ÿ‘€) โ€” same as SIGEV_SIGNAL, except the signal is targeted at the thread whose ID is given in sigev_notify_thread_id, which must be a thread in the same process as the caller. The sigev_notify_thread_id field specifies a kernel thread ID, that is, the value returned by clone(2) or gettid(2). This flag is intended only for use by threading libraries. not for you, bestie, unless you're writing a threading library, in which case slay.
  • Passing sevp as NULL is equivalent to passing a pointer to a sigevent structure where sigev_notify is SIGEV_SIGNAL, sigev_signo is SIGALRM, and sigev_value.sival_int is the timer ID. easy defaults ๐Ÿ’–

๐Ÿซถ RETURN VALUE ๐Ÿซถ

On success, timer_create() returns 0, and the ID of the new timer lands in timerid (she's home ๐Ÿฅน). On failure, -1 is returned, and errno is set to tell you what went wrong.

๐Ÿ’€ ERRORS ๐Ÿ’€

  • EAGAIN โ€” temporary error during kernel allocation of timer structures. just a lil hiccup, try again.
  • EINVAL โ€” clock ID, sigev_notify, sigev_signo, or sigev_notify_thread_id is invalid.
  • ENOMEM โ€” could not allocate memory. ๐Ÿ˜ญ
  • ENOTSUP โ€” the kernel does not support creating a timer against this clockid.
  • EPERM โ€” clockid was CLOCK_REALTIME_ALARM or CLOCK_BOOTTIME_ALARM but the caller did not have the CAP_WAKE_ALARM capability. permissions said no. ๐Ÿšซ

๐ŸŒˆ VERSIONS ๐ŸŒˆ

C library/kernel differences

Part of the implementation of the POSIX timers API is provided by glibc. In particular, check it:

  • Much of the functionality for SIGEV_THREAD is implemented within glibc, rather than in the kernel. (This is necessarily so, since the thread involved in handling the notification is one that must be managed by the C library POSIX threads implementation.) And even though the notification delivered to the process is via a thread, internally the NPTL implementation uses a sigev_notify value of SIGEV_THREAD_ID along with a real-time signal that is reserved by the implementation โ€” see nptl(7).
  • The implementation of the default case where evp is NULL is handled inside glibc, which invokes the underlying system call with a suitably populated sigevent structure. (note: it's written evp here, that's what the page says, don't come for me ๐Ÿซถ)
  • The timer IDs presented at user level are maintained by glibc, which maps these IDs to the timer IDs employed by the kernel. so the IDs you see are glibc's, and she translates.

โญ STANDARDS โญ

POSIX.1-2024. periodt.

๐Ÿ‘‘ HISTORY ๐Ÿ‘‘

Linux 2.6. POSIX.1-2001.

And a lil lore drop: prior to Linux 2.6, glibc provided an incomplete user-space implementation (CLOCK_REALTIME timers only) using POSIX threads. And before glibc 2.17, the implementation falls back to this technique on systems running kernels older than Linux 2.6. ancient history, bestie ๐Ÿ›๏ธ

๐Ÿงš NOTES ๐Ÿงš

A program may create multiple interval timers using timer_create(). collect them like pokรฉmon, honestly.

Timers are not inherited by the child of a fork(2), and they are disarmed and deleted during an execve(2). gone, reduced to atoms.

The kernel preallocates a "queued real-time signal" for each timer created using timer_create(). Consequently, the number of timers is limited by the RLIMIT_SIGPENDING resource limit (see setrlimit(2)). so there IS a ceiling, iykyk.

The timers created by timer_create() are commonly known as "POSIX (interval) timers". The POSIX timers API consists of the following interfaces:

  • timer_create() โ€” create a timer.
  • timer_settime(2) โ€” arm (start) or disarm (stop) a timer.
  • timer_gettime(2) โ€” fetch the time remaining until the next expiration of a timer, along with the interval setting of the timer.
  • timer_getoverrun(2) โ€” return the overrun count for the last timer expiration.
  • timer_delete(2) โ€” disarm and delete a timer.

Since Linux 3.10, the /proc/pid/timers file can be used to list the POSIX timers for the process with PID pid. See proc(5) for further information. go snoop, respectfully ๐Ÿ”

Since Linux 4.10, support for POSIX timers is a configurable option that is enabled by default. Kernel support can be disabled via the CONFIG_POSIX_TIMERS option. so if it's mysteriously missing, that's why ๐Ÿ‘€

โœจ EXAMPLES โœจ

okay bestie, let's get into the actual demo because this is where it gets iconic ๐Ÿ’… The program below takes two arguments: a sleep period in seconds, and a timer frequency in nanoseconds. It establishes a handler for the signal it uses for the timer, blocks that signal, creates and arms a timer that expires with the given frequency, sleeps for the specified number of seconds, and then unblocks the timer signal. Assuming that the timer expired at least once while the program slept, the signal handler will be invoked, and the handler displays some information about the timer notification. The program terminates after one invocation of the signal handler. periodt, no cap โœจ

In the following example run, the program sleeps for 1 second, after creating a timer that has a frequency of 100 nanoseconds. By the time the signal is unblocked and delivered, there have been around ten million overruns. not me being gagged at ten million ๐Ÿ˜ญ

           $ ./a.out 1 100;
           Establishing handler for signal 34
           Blocking signal 34
           timer ID is 0x804c008
           Sleeping for 1 seconds
           Unblocking signal 34
           Caught signal 34
               sival_ptr = 0xbfb174f4;     *sival_ptr = 0x804c008
               overrun count = 10004886

๐Ÿฆ‹ Program source ๐Ÿฆ‹

       #include <err.h>
       #include <signal.h>
       #include <stdint.h>
       #include <stdio.h>
       #include <stdlib.h>
       #include <time.h>
       #include <unistd.h>

       #define CLOCKID CLOCK_REALTIME
       #define SIG SIGRTMIN

       static void
       print_siginfo(siginfo_t *si)
       {
           int      or;
           timer_t  *tidp;

           tidp = si->si_value.sival_ptr;

           printf("    sival_ptr = %p; ", si->si_value.sival_ptr);
           printf("    *sival_ptr = %#jx\n", (uintmax_t) *tidp);

           or = timer_getoverrun(*tidp);
           if (or == -1)
               err(EXIT_FAILURE, "timer_getoverrun");

           printf("    overrun count = %d\n", or);
       }

       static void
       handler(int sig, siginfo_t *si, void *uc)
       {
           /* Note: calling printf() from a signal handler is not safe
              (and should not be done in production programs), since
              printf() is not async-signal-safe; see signal-safety(7).
              Nevertheless, we use printf() here as a simple way of
              showing that the handler was called.  */

           printf("Caught signal %d\n", sig);
           print_siginfo(si);
           signal(sig, SIG_IGN);
       }

       int
       main(int argc, char *argv[])
       {
           timer_t            timerid;
           sigset_t           mask;
           long long          freq_nanosecs;
           struct sigevent    sev;
           struct sigaction   sa;
           struct itimerspec  its;

           if (argc != 3) {
               fprintf(stderr, "Usage: %s <sleep-secs> <freq-nanosecs>\n",
                       argv[0]);
               exit(EXIT_FAILURE);
           }

           /* Establish handler for timer signal.  */

           printf("Establishing handler for signal %d\n", SIG);
           sa.sa_flags = SA_SIGINFO;
           sa.sa_sigaction = handler;
           sigemptyset(&sa.sa_mask);
           if (sigaction(SIG, &sa, NULL) == -1)
               err(EXIT_FAILURE, "sigaction");

           /* Block timer signal temporarily.  */

           printf("Blocking signal %d\n", SIG);
           sigemptyset(&mask);
           sigaddset(&mask, SIG);
           if (sigprocmask(SIG_SETMASK, &mask, NULL) == -1)
               err(EXIT_FAILURE, "sigprocmask");

           /* Create the timer.  */

           sev.sigev_notify = SIGEV_SIGNAL;
           sev.sigev_signo = SIG;
           sev.sigev_value.sival_ptr = &timerid;
           if (timer_create(CLOCKID, &sev, &timerid) == -1)
               err(EXIT_FAILURE, "timer_create");

           printf("timer ID is %#jx\n", (uintmax_t) timerid);

           /* Start the timer.  */

           freq_nanosecs = atoll(argv[2]);
           its.it_value.tv_sec = freq_nanosecs / 1000000000;
           its.it_value.tv_nsec = freq_nanosecs % 1000000000;
           its.it_interval.tv_sec = its.it_value.tv_sec;
           its.it_interval.tv_nsec = its.it_value.tv_nsec;

           if (timer_settime(timerid, 0, &its, NULL) == -1)
                err(EXIT_FAILURE, "timer_settime");

           /* Sleep for a while; meanwhile, the timer may expire
              multiple times.  */

           printf("Sleeping for %d seconds\n", atoi(argv[1]));
           sleep(atoi(argv[1]));

           /* Unlock the timer signal, so that timer notification
              can be delivered.  */

           printf("Unblocking signal %d\n", SIG);
           if (sigprocmask(SIG_UNBLOCK, &mask, NULL) == -1)
               err(EXIT_FAILURE, "sigprocmask");

           exit(EXIT_SUCCESS);
       }

๐ŸŒˆ SEE ALSO ๐ŸŒˆ

bestie, if you're thirsty for more, go sip on these ๐Ÿ“


this glow-up came from Linux man-pages 6.20, dated 2025-10-29 ๐Ÿ’– stay slaying, bestie โœจ๐Ÿ‘‘

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: Linux-man-pages-copyleft
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms