This code (tokio part) is taken verbatim from tokio's webpage. This is working example.
use tokio::{
signal,
sync::mpsc::{UnboundedReceiver, UnboundedSender},
};
async fn tokio_ctrl_c(shutdown_send: UnboundedSender<()>) {
// ... spawn application as separate task ...
//
// application uses shutdown_send in case a shutdown was issued from inside
// the application
match signal::ctrl_c().await {
Ok(()) => {
eprintln!("aaaa");
shutdown_send.send(()).unwrap();
}
Err(err) => {
eprintln!("Unable to listen for shutdown signal: {}", err);
shutdown_send.send(()).unwrap();
// we also shut down in case of error
}
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let (shutdown_send, mut shutdown_recv) = tokio::sync::mpsc::unbounded_channel::<()>();
tokio::spawn(tokio_ctrl_c(shutdown_send.clone()));
let handle = tokio::spawn(async move {
// Do some async work
main_rusb(&mut shutdown_recv);
"return value"
});
Ok(())
}
fn main_rusb(shutdown_recv: &mut UnboundedReceiver<()>) {
loop {
eprintln!("main_rusb");
std::thread::sleep(std::time::Duration::from_secs(2));
if let Ok(_) = shutdown_recv.try_recv() {
break;
}
}
}
Unfortunately if it is not run from main thread this behaves in a way that Ctrl+C doesn't get triggered. Could somebody explain why and how to fix it?
Thanks