2019-05-14 10:27:36 -07:00
|
|
|
#![deny(warnings, rust_2018_idioms)]
|
2019-07-03 10:40:59 -07:00
|
|
|
#![feature(async_await)]
|
2019-05-14 10:27:36 -07:00
|
|
|
|
2019-07-03 10:40:59 -07:00
|
|
|
use futures_util::stream::StreamExt;
|
2016-09-08 17:13:18 -07:00
|
|
|
|
2017-06-08 21:32:50 +02:00
|
|
|
/// how many signals to handle before exiting
|
|
|
|
|
const STOP_AFTER: u64 = 10;
|
|
|
|
|
|
2019-07-03 10:40:59 -07:00
|
|
|
#[tokio::main]
|
2019-07-10 11:21:06 -07:00
|
|
|
async fn main() {
|
2017-06-07 21:20:25 +02:00
|
|
|
// tokio_signal provides a convenience builder for Ctrl+C
|
2017-06-08 15:57:06 +02:00
|
|
|
// this even works cross-platform: linux and windows!
|
|
|
|
|
//
|
2019-07-09 08:48:46 -07:00
|
|
|
// `CtrlC::new()` produces a `Future` of the actual stream-initialisation
|
2019-07-03 10:40:59 -07:00
|
|
|
// so first we await until the signal is ready.
|
2019-07-10 11:21:06 -07:00
|
|
|
let endless_stream = tokio_signal::CtrlC::new().await.unwrap();
|
2017-06-08 21:32:50 +02:00
|
|
|
// don't keep going forever: convert the endless stream to a bounded one.
|
2019-07-09 08:48:46 -07:00
|
|
|
let mut limited_stream = endless_stream.take(STOP_AFTER);
|
2017-06-08 21:32:50 +02:00
|
|
|
|
|
|
|
|
// how many Ctrl+C have we received so far?
|
|
|
|
|
let mut counter = 0;
|
2016-09-08 17:13:18 -07:00
|
|
|
|
2018-05-03 19:12:23 +02:00
|
|
|
println!(
|
2019-07-07 18:49:20 +02:00
|
|
|
"This program is now waiting for you to press Ctrl+C {0} times. \
|
|
|
|
|
Terminate by repeating Ctrl+C {0} times, or ahead of time by opening \
|
|
|
|
|
a second terminal and issuing `pkill -sigkil ctrl-c`.",
|
2018-05-03 19:12:23 +02:00
|
|
|
STOP_AFTER
|
|
|
|
|
);
|
2017-06-07 21:18:26 +02:00
|
|
|
|
2017-06-07 21:20:25 +02:00
|
|
|
// Up until now, we haven't really DONE anything, just prepared
|
2019-07-09 08:48:46 -07:00
|
|
|
// our futures, now it's time to actually await the results!
|
|
|
|
|
while let Some(_) = limited_stream.next().await {
|
|
|
|
|
// Note how we manipulate the counter without any fancy synchronisation.
|
|
|
|
|
// The borrowchecker realises there can't be any conflicts, so the closure
|
|
|
|
|
// can just capture it.
|
|
|
|
|
counter += 1;
|
|
|
|
|
println!(
|
|
|
|
|
"Ctrl+C received {} times! {} more before exit",
|
|
|
|
|
counter,
|
|
|
|
|
STOP_AFTER - counter
|
|
|
|
|
);
|
|
|
|
|
}
|
2017-06-07 21:20:51 +02:00
|
|
|
|
2017-06-08 21:32:50 +02:00
|
|
|
println!("Stream ended, quiting the program.");
|
2016-09-08 17:13:18 -07:00
|
|
|
}
|