mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-27 00:00:12 +02:00
This avoids having consumers import libc for common signals, and it improves discoverability since users need not be aware that libc contains all supported constants.
46 lines
1.4 KiB
Rust
46 lines
1.4 KiB
Rust
#![warn(rust_2018_idioms)]
|
|
#![feature(async_await)]
|
|
|
|
//! A small example of how to listen for two signals at the same time
|
|
|
|
// A trick to not fail build on non-unix platforms when using unix-specific features.
|
|
#[cfg(unix)]
|
|
mod platform {
|
|
use futures_util::stream::{self, StreamExt};
|
|
use tokio_signal::unix::{Signal, SignalKind};
|
|
|
|
pub async fn main() {
|
|
// Create a stream for each of the signals we'd like to handle.
|
|
let sigint = Signal::new(SignalKind::sigint()).unwrap().map(|_| "SIGINT");
|
|
let sigterm = Signal::new(SignalKind::sigterm())
|
|
.unwrap()
|
|
.map(|_| "SIGTERM");
|
|
|
|
// Use the `select` combinator to merge these two streams into one
|
|
let stream = stream::select(sigint, sigterm);
|
|
|
|
// Wait for a signal to arrive
|
|
println!("Waiting for SIGINT or SIGTERM");
|
|
println!(
|
|
" TIP: use `pkill -sigint multiple` from a second terminal \
|
|
to send a SIGINT to all processes named 'multiple' \
|
|
(i.e. this binary)"
|
|
);
|
|
let (item, _rest) = stream.into_future().await;
|
|
|
|
// Figure out which signal we received
|
|
let msg = item.ok_or("received no signal").unwrap();
|
|
println!("received {}", msg);
|
|
}
|
|
}
|
|
|
|
#[cfg(not(unix))]
|
|
mod platform {
|
|
pub async fn main() {}
|
|
}
|
|
|
|
#[tokio::main]
|
|
async fn main() {
|
|
platform::main().await
|
|
}
|