smol/examples/linux-timerfd.rs

45 lines
1.3 KiB
Rust
Raw Normal View History

2020-04-21 15:51:07 +00:00
// TODO: document
2020-03-31 16:04:16 +00:00
#[cfg(target_os = "linux")]
fn main() -> std::io::Result<()> {
use std::io;
use std::os::unix::io::AsRawFd;
use std::time::{Duration, Instant};
use smol::Async;
use timerfd::{SetTimeFlags, TimerFd, TimerState};
/// Converts a `nix::Error` into `std::io::Error`.
fn io_err(err: nix::Error) -> io::Error {
match err {
nix::Error::Sys(code) => code.into(),
err => io::Error::new(io::ErrorKind::Other, Box::new(err)),
}
}
2020-04-01 19:40:27 +00:00
/// Sleeps using a `TimerFd`.
2020-03-31 16:04:16 +00:00
async fn sleep(dur: Duration) -> io::Result<()> {
// Create a timer.
let mut timer = TimerFd::new()?;
timer.set_state(TimerState::Oneshot(dur), SetTimeFlags::Default);
// When the timer fires, a 64-bit integer can be read from it.
Async::new(timer)?
2020-04-08 14:40:03 +00:00
.with(|t| nix::unistd::read(t.as_raw_fd(), &mut [0u8; 8]).map_err(io_err))
2020-03-31 16:04:16 +00:00
.await?;
Ok(())
}
smol::run(async {
let start = Instant::now();
println!("Sleeping...");
sleep(Duration::from_secs(1)).await?;
println!("Woke up after {:?}", start.elapsed());
Ok(())
})
}
#[cfg(not(target_os = "linux"))]
fn main() {
println!("This example works only on Linux!");
}