Skip to content

timerfd_create()

Purpose

Creates a file descriptor that becomes readable when a timer expires.

#include <sys/timerfd.h>

Prototype

int timerfd_create(int clockid, int flags);

Parameters

  • clockid: commonly CLOCK_MONOTONIC or CLOCK_REALTIME.
  • flags: commonly TFD_CLOEXEC, TFD_NONBLOCK, or both.

Return Value

  • Success: returns a timer fd.
  • Failure: returns -1 and sets errno.

Minimal Example

int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);

Common Pitfalls

  • Prefer CLOCK_MONOTONIC for relative timers.
  • Read the timer fd after it becomes readable, otherwise epoll will keep reporting it.
  • The read size must be sizeof(uint64_t).