smol/examples/unix-signal.rs

33 lines
790 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::net::UnixStream;
2020-07-20 17:20:29 +00:00
use smol::{block_on, io::AsyncReadExt, Async};
2020-04-06 20:19:54 +00:00
2020-07-14 19:19:01 +00:00
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()?;
signal_hook::pipe::register(signal_hook::SIGINT, a)?;
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!");
}