Tokio: how to wait for multiple signals?

I want to wait for SIGINT and SIGTERM. Is there a simple way to wait for an arbitrary number of signals?

This is a repost of this question because it was never answered.

You can use tokio::select! to wait for various events.

use tokio::signal::unix::{signal, SignalKind};
tokio::select! {
    _ = signal(SignalKind::interrupt())?.recv() => println!("SIGINT"),
    _ = signal(SignalKind::terminate())?.recv() => println!("SIGTERM"),
println!("terminating the process...");

If you don't mind the dependency, there are crates for this. signal_hook - Rust is one of them, and it comes with async adapters for various runtimes, for instance signal_hook_tokio - Rust.

tokio::signal is backed by the signal-hook-registry crate which is the backend of the signal-hook crate.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.