Debian Codegraph @

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