Debian Codegraph @

src/sys/timerfd.rs

raw
1 //! Timer API via file descriptors.
2 //!
3 //! Timer FD is a Linux-only API to create timers and get expiration
4 //! notifications through file descriptors.
5 //!
6 //! For more documentation, please read [timerfd_create(2)](https://man7.org/linux/man-pages/man2/timerfd_create.2.html).
7 //!
8 //! # Examples
9 //!
10 //! Create a new one-shot timer that expires after 1 second.
11 //! ```
12 //! # use std::os::unix::io::AsRawFd;
13 //! # use nix::sys::timerfd::{TimerFd, ClockId, TimerFlags, TimerSetTimeFlags,
14 //! # Expiration};
15 //! # use nix::sys::time::{TimeSpec, TimeValLike};
16 //! # use nix::unistd::read;
17 //! #
18 //! // We create a new monotonic timer.
19 //! let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty())
20 //! .unwrap();
21 //!
22 //! // We set a new one-shot timer in 1 seconds.
23 //! timer.set(
24 //! Expiration::OneShot(TimeSpec::seconds(1)),
25 //! TimerSetTimeFlags::empty()
26 //! ).unwrap();
27 //!
28 //! // We wait for the timer to expire.
29 //! timer.wait().unwrap();
30 //! ```
31 use crate::sys::time::timer::TimerSpec;
32 pub use crate::sys::time::timer::{Expiration, TimerSetTimeFlags};
33 use crate::unistd::read;
34 use crate::{errno::Errno, Result};
35 use libc::c_int;
36 use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd};
37
38 /// A timerfd instance. This is also a file descriptor, you can feed it to
39 /// other interfaces taking file descriptors as arguments, [`epoll`] for example.
40 ///
41 /// [`epoll`]: crate::sys::epoll
42 #[derive(Debug)]
43 pub struct TimerFd {
44 fd: OwnedFd,
45 }
46
47 impl AsFd for TimerFd {
48 fn as_fd(&self) -> BorrowedFd<'_> {
49 self.fd.as_fd()
50 }
51 }
52
53 impl FromRawFd for TimerFd {
54 unsafe fn from_raw_fd(fd: RawFd) -> Self {
55 TimerFd {
56 fd: unsafe { OwnedFd::from_raw_fd(fd) },
57 }
58 }
59 }
60
61 impl From<TimerFd> for OwnedFd {
62 fn from(value: TimerFd) -> Self {
63 value.fd
64 }
65 }
66
67 libc_enum! {
68 /// The type of the clock used to mark the progress of the timer. For more
69 /// details on each kind of clock, please refer to [timerfd_create(2)](https://man7.org/linux/man-pages/man2/timerfd_create.2.html).
70 #[repr(i32)]
71 #[non_exhaustive]
72 pub enum ClockId {
73 /// A settable system-wide real-time clock.
74 CLOCK_REALTIME,
75 /// A non-settable monotonically increasing clock.
76 ///
77 /// Does not change after system startup.
78 /// Does not measure time while the system is suspended.
79 CLOCK_MONOTONIC,
80 /// Like `CLOCK_MONOTONIC`, except that `CLOCK_BOOTTIME` includes the time
81 /// that the system was suspended.
82 CLOCK_BOOTTIME,
83 /// Like `CLOCK_REALTIME`, but will wake the system if it is suspended.
84 CLOCK_REALTIME_ALARM,
85 /// Like `CLOCK_BOOTTIME`, but will wake the system if it is suspended.
86 CLOCK_BOOTTIME_ALARM,
87 }
88 }
89
90 libc_bitflags! {
91 /// Additional flags to change the behaviour of the file descriptor at the
92 /// time of creation.
93 pub struct TimerFlags: c_int {
94 /// Set the `O_NONBLOCK` flag on the open file description referred to by the new file descriptor.
95 TFD_NONBLOCK;
96 /// Set the `FD_CLOEXEC` flag on the file descriptor.
97 TFD_CLOEXEC;
98 }
99 }
100
101 impl TimerFd {
102 /// Creates a new timer based on the clock defined by `clockid`. The
103 /// underlying fd can be assigned specific flags with `flags` (CLOEXEC,
104 /// NONBLOCK). The underlying fd will be closed on drop.
105 #[doc(alias("timerfd_create"))]
106 pub fn new(clockid: ClockId, flags: TimerFlags) -> Result<Self> {
107 Errno::result(unsafe {
108 libc::timerfd_create(clockid as i32, flags.bits())
109 })
110 .map(|fd| Self {
111 fd: unsafe { OwnedFd::from_raw_fd(fd) },
112 })
113 }
114
115 /// Sets a new alarm on the timer.
116 ///
117 /// # Types of alarm
118 ///
119 /// There are 3 types of alarms you can set:
120 ///
121 /// - one shot: the alarm will trigger once after the specified amount of
122 /// time.
123 /// Example: I want an alarm to go off in 60s and then disable itself.
124 ///
125 /// - interval: the alarm will trigger every specified interval of time.
126 /// Example: I want an alarm to go off every 60s. The alarm will first
127 /// go off 60s after I set it and every 60s after that. The alarm will
128 /// not disable itself.
129 ///
130 /// - interval delayed: the alarm will trigger after a certain amount of
131 /// time and then trigger at a specified interval.
132 /// Example: I want an alarm to go off every 60s but only start in 1h.
133 /// The alarm will first trigger 1h after I set it and then every 60s
134 /// after that. The alarm will not disable itself.
135 ///
136 /// # Relative vs absolute alarm
137 ///
138 /// If you do not set any `TimerSetTimeFlags`, then the `TimeSpec` you pass
139 /// to the `Expiration` you want is relative. If however you want an alarm
140 /// to go off at a certain point in time, you can set `TFD_TIMER_ABSTIME`.
141 /// Then the one shot TimeSpec and the delay TimeSpec of the delayed
142 /// interval are going to be interpreted as absolute.
143 ///
144 /// # Cancel on a clock change
145 ///
146 /// If you set a `TFD_TIMER_CANCEL_ON_SET` alongside `TFD_TIMER_ABSTIME`
147 /// and the clock for this timer is `CLOCK_REALTIME` or `CLOCK_REALTIME_ALARM`,
148 /// then this timer is marked as cancelable if the real-time clock undergoes
149 /// a discontinuous change.
150 ///
151 /// # Disabling alarms
152 ///
153 /// Note: Only one alarm can be set for any given timer. Setting a new alarm
154 /// actually removes the previous one.
155 ///
156 /// Note: Setting a one shot alarm with a 0s TimeSpec disables the alarm
157 /// altogether.
158 #[doc(alias("timerfd_settime"))]
159 pub fn set(
160 &self,
161 expiration: Expiration,
162 flags: TimerSetTimeFlags,
163 ) -> Result<()> {
164 let timerspec: TimerSpec = expiration.into();
165 Errno::result(unsafe {
166 libc::timerfd_settime(
167 self.fd.as_fd().as_raw_fd(),
168 flags.bits(),
169 timerspec.as_ref(),
170 std::ptr::null_mut(),
171 )
172 })
173 .map(drop)
174 }
175
176 /// Get the parameters for the alarm currently set, if any.
177 #[doc(alias("timerfd_gettime"))]
178 pub fn get(&self) -> Result<Option<Expiration>> {
179 let mut timerspec = TimerSpec::none();
180 Errno::result(unsafe {
181 libc::timerfd_gettime(
182 self.fd.as_fd().as_raw_fd(),
183 timerspec.as_mut(),
184 )
185 })
186 .map(|_| {
187 if timerspec.as_ref().it_interval.tv_sec == 0
188 && timerspec.as_ref().it_interval.tv_nsec == 0
189 && timerspec.as_ref().it_value.tv_sec == 0
190 && timerspec.as_ref().it_value.tv_nsec == 0
191 {
192 None
193 } else {
194 Some(timerspec.into())
195 }
196 })
197 }
198
199 /// Remove the alarm if any is set.
200 #[doc(alias("timerfd_settime"))]
201 pub fn unset(&self) -> Result<()> {
202 Errno::result(unsafe {
203 libc::timerfd_settime(
204 self.fd.as_fd().as_raw_fd(),
205 TimerSetTimeFlags::empty().bits(),
206 TimerSpec::none().as_ref(),
207 std::ptr::null_mut(),
208 )
209 })
210 .map(drop)
211 }
212
213 /// Wait for the configured alarm to expire.
214 ///
215 /// Note: If the alarm is unset, then you will wait forever.
216 pub fn wait(&self) -> Result<()> {
217 while let Err(e) = read(&self.fd, &mut [0u8; 8]) {
218 if e == Errno::ECANCELED {
219 break;
220 }
221 if e != Errno::EINTR {
222 return Err(e);
223 }
224 }
225
226 Ok(())
227 }
228
229
230 /// Constructs a `TimerFd` wrapping an existing `OwnedFd`.
231 ///
232 /// # Safety
233 ///
234 /// `OwnedFd` is a valid `TimerFd`.
235 pub unsafe fn from_owned_fd(fd: OwnedFd) -> Self {
236 Self {
237 fd
238 }
239 }
240 }