2019-05-14 10:27:36 -07:00
|
|
|
#![deny(warnings, rust_2018_idioms)]
|
2019-07-03 10:40:59 -07:00
|
|
|
#![feature(async_await)]
|
2017-06-29 22:56:15 -07:00
|
|
|
|
2019-05-14 10:27:36 -07:00
|
|
|
//! A small example of how to listen for two signals at the same time
|
2017-06-29 22:56:15 -07:00
|
|
|
|
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 {
|
2019-07-03 10:40:59 -07:00
|
|
|
use futures_util::stream::{self, StreamExt};
|
2018-09-02 11:32:50 +02:00
|
|
|
use tokio_signal::unix::{Signal, SIGINT, SIGTERM};
|
2017-06-29 22:56:15 -07:00
|
|
|
|
2019-07-10 11:21:06 -07:00
|
|
|
pub async fn main() {
|
2018-09-02 11:32:50 +02:00
|
|
|
// Create a stream for each of the signals we'd like to handle.
|
2019-07-10 11:21:06 -07:00
|
|
|
let sigint = Signal::new(SIGINT).await.unwrap();
|
|
|
|
|
let sigterm = Signal::new(SIGTERM).await.unwrap();
|
2017-06-29 22:56:15 -07:00
|
|
|
|
2018-09-02 11:32:50 +02:00
|
|
|
// Use the `select` combinator to merge these two streams into one
|
2019-07-03 10:40:59 -07:00
|
|
|
let stream = stream::select(sigint, sigterm);
|
2017-06-29 22:56:15 -07:00
|
|
|
|
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 \
|
2019-02-21 11:56:15 -08:00
|
|
|
to send a SIGINT to all processes named 'multiple' \
|
|
|
|
|
(i.e. this binary)"
|
2018-09-02 11:32:50 +02:00
|
|
|
);
|
2019-07-03 10:40:59 -07:00
|
|
|
let (item, _rest) = stream.into_future().await;
|
2018-09-02 11:32:50 +02:00
|
|
|
|
|
|
|
|
// Figure out which signal we received
|
2019-07-10 11:21:06 -07:00
|
|
|
let item = item.ok_or("received no signal").unwrap();
|
2018-09-02 11:32:50 +02:00
|
|
|
if item == SIGINT {
|
|
|
|
|
println!("received SIGINT");
|
|
|
|
|
} else {
|
|
|
|
|
assert_eq!(item, SIGTERM);
|
|
|
|
|
println!("received SIGTERM");
|
|
|
|
|
}
|
2017-06-29 22:56:15 -07:00
|
|
|
}
|
2018-09-02 11:32:50 +02:00
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(not(unix))]
|
|
|
|
|
mod platform {
|
2019-07-10 11:21:06 -07:00
|
|
|
pub async fn main() {}
|
2018-09-02 11:32:50 +02:00
|
|
|
}
|
|
|
|
|
|
2019-07-03 10:40:59 -07:00
|
|
|
#[tokio::main]
|
2019-07-10 11:21:06 -07:00
|
|
|
async fn main() {
|
2019-07-03 10:40:59 -07:00
|
|
|
platform::main().await
|
2017-06-29 22:56:15 -07:00
|
|
|
}
|