Files
tokio/tokio-signal/examples/multiple.rs
T

53 lines
1.6 KiB
Rust
Raw Normal View History

//! A small example of how to listen for two signals at the same time
extern crate futures;
2018-09-02 11:32:50 +02:00
extern crate tokio;
extern crate tokio_signal;
2018-09-02 11:32:50 +02:00
// A trick to not fail build on non-unix platforms when using unix-specific features.
#[cfg(unix)]
mod platform {
2018-09-02 11:32:50 +02:00
use futures::{Future, Stream};
use tokio_signal::unix::{Signal, SIGINT, SIGTERM};
pub fn main() -> Result<(), Box<::std::error::Error>> {
2018-09-02 11:32:50 +02:00
// Create a stream for each of the signals we'd like to handle.
let sigint = Signal::new(SIGINT).flatten_stream();
let sigterm = Signal::new(SIGTERM).flatten_stream();
2018-09-02 11:32:50 +02:00
// Use the `select` combinator to merge these two streams into one
let stream = sigint.select(sigterm);
2018-09-02 11:32:50 +02:00
// Wait for a signal to arrive
println!("Waiting for SIGINT or SIGTERM");
println!(
" TIP: use `pkill -sigint multiple` from a second terminal \
2018-05-03 19:12:23 +02:00
to send a SIGINT to all processes named 'multiple' \
(i.e. this binary)"
2018-09-02 11:32:50 +02:00
);
let (item, _rest) = ::tokio::runtime::current_thread::block_on_all(stream.into_future())
.map_err(|_| "failed to wait for signals")?;
2018-09-02 11:32:50 +02:00
// Figure out which signal we received
let item = item.ok_or("received no signal")?;
2018-09-02 11:32:50 +02:00
if item == SIGINT {
println!("received SIGINT");
} else {
assert_eq!(item, SIGTERM);
println!("received SIGTERM");
}
Ok(())
}
2018-09-02 11:32:50 +02:00
}
#[cfg(not(unix))]
mod platform {
pub fn main() -> Result<(), Box<::std::error::Error>> {Ok(())}
2018-09-02 11:32:50 +02:00
}
fn main() -> Result<(), Box<std::error::Error>> {
2018-09-02 11:32:50 +02:00
platform::main()
}