From 9bf3228f730c2bc7355c21610e5ca3f62154f037 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 29 Jun 2017 22:56:15 -0700 Subject: [PATCH] signal: Add an example for waiting on two signals Relies on `Stream::select` to merge streams. Closes alexcrichton/tokio-signal#16 --- examples/multiple.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 examples/multiple.rs diff --git a/examples/multiple.rs b/examples/multiple.rs new file mode 100644 index 000000000..3a67db789 --- /dev/null +++ b/examples/multiple.rs @@ -0,0 +1,38 @@ +//! A small example of how to listen for two signals at the same time + +extern crate futures; +extern crate tokio_core; +extern crate tokio_signal; + +use futures::{Stream, Future}; +use tokio_core::reactor::Core; +use tokio_signal::unix::{Signal, SIGINT, SIGTERM}; + +fn main() { + let mut core = Core::new().unwrap(); + let handle = core.handle(); + + // Create a stream for each of the signals we'd like to handle. + let sigint = Signal::new(SIGINT, &handle).flatten_stream(); + let sigterm = Signal::new(SIGTERM, &handle).flatten_stream(); + + // Use the `select` combinator to merge these two streams into one + let stream = sigint.select(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) = core.run(stream.into_future()).ok().unwrap(); + + // Figure out which signal we received + let item = item.unwrap(); + if item == SIGINT { + println!("received SIGINT"); + } else { + assert_eq!(item, SIGTERM); + println!("received SIGTERM"); + } +} +