Documentation
¶
Overview ¶
Package timerfd provides Linux descriptor timers with expiration counts, Go polling, and read deadlines. It requires Linux 7.0 or later and permitted timerfd, clock_gettime, and polling operations.
New creates an owned, disarmed Timer for Monotonic, Realtime, or Boottime. SetAfter arms relatively; SetAt uses a tagged Instant from the same Linux clock, not Go's monotonic time origin. State and setters report relative remaining time and interval. Close the timer when done.
Read consumes native-endian eight-byte expiration records; ReadExpirations decodes their counts. Reads wait through Go's poller, bounded by SetReadDeadline or Close. I/O deadlines are independent of timer arming. Register adds the timer to an explicit epoll readiness set while keeping descriptor access private. The registration has an independent lifetime.
See timerfd_create(2) for clock-change, count, and timer semantics.
Index ¶
- type Clock
- type Instant
- type SetFlags
- type State
- type Timer
- func (t *Timer) Close() error
- func (t *Timer) Disarm() (State, error)
- func (t *Timer) Read(p []byte) (int, error)
- func (t *Timer) ReadExpirations() (uint64, error)
- func (t *Timer) Register(poller *epoll.Poller, interests epoll.Events) (*epoll.Registration, error)
- func (t *Timer) SetAfter(initial, interval time.Duration) (State, error)
- func (t *Timer) SetAt(deadline Instant, interval time.Duration, flags SetFlags) (State, error)
- func (t *Timer) SetReadDeadline(deadline time.Time) error
- func (t *Timer) State() (State, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Clock ¶
type Clock uint8
Clock selects a Linux timer clock. The zero value is Monotonic. Clock values are exclusive, not a bitmask or raw Linux clock IDs.
const Boottime Clock = 2
Boottime is like Monotonic but includes suspend time (Linux CLOCK_BOOTTIME). It does not wake a suspended system.
const Monotonic Clock = 0
Monotonic measures time since an unspecified origin, excluding suspend time (Linux CLOCK_MONOTONIC). It is unaffected by discontinuous wall-clock changes.
const Realtime Clock = 1
Realtime measures wall-clock time since the Unix epoch (Linux CLOCK_REALTIME). Absolute timers follow changes to this clock.
type Instant ¶
type Instant struct {
// Clock must match the timer even when the timestamp disarms it.
Clock Clock
// Seconds counts whole seconds from Clock's origin.
Seconds int64
// Nanoseconds is the fractional part, normalized into [0, 1e9).
Nanoseconds int64
}
Instant is an absolute reading of Clock in seconds and nanoseconds from its origin. Nanoseconds must be in [0, 1e9). SetAt requires a nonnegative value representable as signed 64-bit nanoseconds; larger values fail with EOVERFLOW instead of being silently clamped by Linux. A zero timestamp disarms. Realtime uses the Unix epoch; other clocks must not use time.Time.Unix values.
type SetFlags ¶
type SetFlags uint8
SetFlags controls absolute arming. The zero value selects no extra behavior.
const CancelOnSet SetFlags = 1
CancelOnSet requests ECANCELED on a read after a discontinuous Realtime clock change (Linux TFD_TIMER_CANCEL_ON_SET). It is valid only for SetAt on a Realtime timer. It does not detect gradual clock adjustments.
type State ¶
type State struct {
// Remaining is relative to the query, regardless of the arming mode.
Remaining time.Duration
// Interval is the repeat period; zero selects a one-shot.
Interval time.Duration
}
State reports relative time until the next expiration and the repeat interval, even when armed absolutely. An expired one-shot has zero Remaining; this does not imply that there are no unread expirations.
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
Timer owns a Linux timerfd. Its methods are safe for concurrent use; reads compete for counts and sequences of calls are not transactions. Do not copy a Timer after first use. The zero value owns no descriptor and reports os.ErrInvalid. Nil receivers are unsupported.
Valid operations after Close match os.ErrClosed. Invalid arguments take precedence after Close. Syscall failures retain errno through os.PathError for errors.Is/errors.As; permission errors are not classified as unsupported.
Example ¶
package main
import (
"fmt"
"time"
"github.com/alexfalkowski/go-linux/v2/timerfd"
)
func main() {
timer, err := timerfd.New(timerfd.Monotonic)
if err != nil {
panic(err)
}
defer timer.Close()
if err := timer.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
panic(err)
}
if _, err := timer.SetAfter(10*time.Millisecond, 0); err != nil {
panic(err)
}
count, err := timer.ReadExpirations()
if err != nil {
panic(err)
}
fmt.Println("expirations:", count)
}
Output: expirations: 1
func New ¶
New creates a disarmed timer using timerfd_create(2). The caller owns the result and must close it. Unknown clocks fail with os.ErrInvalid before creation. Descriptors are atomically nonblocking and close-on-exec, while Read waits through Go's poller. If polling/deadlines cannot be established, New closes the descriptor and returns the error without a fallback.
func (*Timer) Close ¶
Close releases the owned descriptor and interrupts poll-blocked reads with os.ErrClosed. Repeated Close also matches os.ErrClosed. The kernel destroys the timer when its last descriptor closes.
func (*Timer) Disarm ¶
Disarm stops the timer, clears its interval and unread expirations, and returns its previous state using SetAfter(0, 0). It does not wake a waiting Read; use a read deadline or Close to interrupt a reader.
func (*Timer) Read ¶
Read consumes one timerfd_create(2) expiration record. It requires at least eight bytes and normally returns eight in native byte order, leaving the buffer tail untouched. Smaller buffers, including nil, fail with EINVAL without consumption. With no expirations it waits for an expiration, a read deadline, or Close. Rearming/disarming resets unread counts.
A canceled Realtime timer returns ECANCELED. Without CancelOnSet, a backward Realtime jump can instead produce (0, nil); this is not permanent EOF.
func (*Timer) ReadExpirations ¶
ReadExpirations decodes one destructive Read, returning zero on error. A zero-byte clock-change result becomes io.ErrNoProgress, not a count or EOF.
func (*Timer) Register ¶
Register borrows this timer to create a registration with epoll.Poller.Add's semantics. Readable reports unread expirations or a pending clock cancellation; use Read or ReadExpirations to consume the result. The caller owns the registration and must close it or its poller separately. Closing the timer leaves the registration and kernel timer alive; closing the registration or poller leaves this timer open. Arming, flags, and read deadlines are unchanged.
A nil poller, zero timer, or unknown interests match os.ErrInvalid. Other validation and errors follow Poller.Add. Failure returns nil and leaves the timer open. Concurrent reads or rearming can consume or clear readiness before subsequent I/O; bound that I/O with its own read deadline, independently of Poller.Wait's timeout.
Example ¶
package main
import (
"fmt"
"time"
"github.com/alexfalkowski/go-linux/v2/epoll"
"github.com/alexfalkowski/go-linux/v2/timerfd"
)
func main() {
timer, err := timerfd.New(timerfd.Monotonic)
if err != nil {
panic(err)
}
defer timer.Close()
poller, err := epoll.New()
if err != nil {
panic(err)
}
defer poller.Close()
registration, err := timer.Register(poller, epoll.Readable)
if err != nil {
panic(err)
}
defer registration.Close()
if err := timer.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
panic(err)
}
if _, err := timer.SetAfter(time.Millisecond, 0); err != nil {
panic(err)
}
events := make([]epoll.Event, 1)
n, err := poller.Wait(events, time.Second)
if err != nil {
panic(err)
}
fmt.Println("registered timer:", events[:n][0].Registration == registration)
count, err := timer.ReadExpirations()
if err != nil {
panic(err)
}
fmt.Println("expirations:", count)
}
Output: registered timer: true expirations: 1
func (*Timer) SetAfter ¶
SetAfter arms a relative timer using timerfd_settime(2) and returns its previous state from the same syscall. Zero initial disarms, even if interval is nonzero; zero interval selects a one-shot. Negative durations fail with os.ErrInvalid without changing the timer. Arming resets unread expirations.
Setters may report EOVERFLOW after the change has taken effect if the old kernel state cannot fit time.Duration. On error the returned State is zero. A pending clock cancellation can cause ECANCELED even though Linux applied the new settings; inspect State before deciding whether to retry.
func (*Timer) SetAt ¶
SetAt arms an absolute timer using timerfd_settime(2) and returns its previous relative state. The timestamp's clock must match this timer; use Now to obtain the correct origin. Zero seconds and nanoseconds disarm; a nonzero past deadline expires immediately. Interval is always relative.
Negative or unnormalized timestamps, mismatched clocks, negative intervals, and invalid flags fail with os.ErrInvalid. Timestamps beyond signed 64-bit nanoseconds fail with EOVERFLOW. These validation errors leave the timer unchanged. CancelOnSet is accepted only on Realtime timers. Other setter effects and errors follow SetAfter, including ECANCELED after rearming.
Example ¶
package main
import (
"fmt"
"github.com/alexfalkowski/go-linux/v2/timerfd"
)
func main() {
timer, err := timerfd.New(timerfd.Boottime)
if err != nil {
panic(err)
}
defer timer.Close()
deadline, err := timerfd.Now(timerfd.Boottime)
if err != nil {
panic(err)
}
deadline.Seconds++
if _, err := timer.SetAt(deadline, 0, 0); err != nil {
panic(err)
}
previous, err := timer.Disarm()
if err != nil {
panic(err)
}
fmt.Println("one-shot:", previous.Interval == 0)
}
Output: one-shot: true
func (*Timer) SetReadDeadline ¶
SetReadDeadline wraps os.File.SetReadDeadline for pending and future reads. Zero clears it; expired reads match os.ErrDeadlineExceeded. This Go I/O deadline does not change the kernel timer or affect arming/state operations.