smol/examples/unix-signal.rs

34 lines
918 B
Rust
Raw Normal View History

2020-04-26 17:37:29 +00:00
//! Uses the `signal-hook` crate to catch the Ctrl-C signal.
//!
//! Run with:
//!
//! ```
//! cargo run --example unix-signal
//! ```
2020-04-06 20:19:54 +00:00
#[cfg(unix)]
fn main() -> std::io::Result<()> {
use std::os::unix::{io::AsRawFd, net::UnixStream};
2020-04-06 20:19:54 +00:00
2020-07-23 10:24:16 +00:00
use smol::{prelude::*, Async};
2020-04-06 20:19:54 +00:00
2020-08-26 21:59:49 +00:00
smol::block_on(async {
2020-04-26 17:37:29 +00:00
// Create a Unix stream that receives a byte on each signal occurrence.
2020-04-06 20:19:54 +00:00
let (a, mut b) = Async::<UnixStream>::pair()?;
// Async isn't IntoRawFd, but it is AsRawFd, so let's pass the raw fd directly.
signal_hook::low_level::pipe::register_raw(signal_hook::consts::SIGINT, a.as_raw_fd())?;
2020-04-26 17:37:29 +00:00
println!("Waiting for Ctrl-C...");
2020-04-06 20:19:54 +00:00
2020-06-20 14:29:04 +00:00
// Receive a byte that indicates the Ctrl-C signal occurred.
2020-04-06 20:19:54 +00:00
b.read_exact(&mut [0]).await?;
2020-04-26 17:37:29 +00:00
println!("Done!");
2020-04-06 20:19:54 +00:00
Ok(())
})
}
#[cfg(not(unix))]
fn main() {
println!("This example works only on Unix systems!");
}