pub struct SignalHandler { /* private fields */ }Expand description
A handler for listening to multiple Unix signals, and providing a future for receiving them.
This is useful for applications that need to listen for multiple signals, and want to react to them in a non-blocking way. Typically you would need to use a tokio::select{} to listen for multiple signals, but this provides a more ergonomic interface for doing so.
After a signal is received you can poll the handler again to wait for another signal. Dropping the handle will cancel the signal subscription
§Example
use scuffle_signal::SignalHandler;
use tokio::signal::unix::SignalKind;
let mut handler = SignalHandler::new()
.with_signal(SignalKind::interrupt())
.with_signal(SignalKind::terminate());
// Wait for a signal to be received
let signal = handler.await;
// Handle the signal
let interrupt = SignalKind::interrupt();
let terminate = SignalKind::terminate();
match signal {
interrupt => {
// Handle SIGINT
println!("received SIGINT");
},
terminate => {
// Handle SIGTERM
println!("received SIGTERM");
},
}Implementations§
Source§impl SignalHandler
impl SignalHandler
Sourcepub fn with_signals(signals: impl IntoIterator<Item = SignalKind>) -> Self
pub fn with_signals(signals: impl IntoIterator<Item = SignalKind>) -> Self
Create a new SignalHandler with the given signals.
Sourcepub fn with_signal(self, kind: SignalKind) -> Self
pub fn with_signal(self, kind: SignalKind) -> Self
Add a signal to the handler.
If the signal is already in the handler, it will not be added again.
Sourcepub fn add_signal(&mut self, kind: SignalKind) -> &mut Self
pub fn add_signal(&mut self, kind: SignalKind) -> &mut Self
Add a signal to the handler.
If the signal is already in the handler, it will not be added again.
Sourcepub async fn recv(&mut self) -> SignalKind
pub async fn recv(&mut self) -> SignalKind
Wait for a signal to be received. This is equivilant to calling (&mut handler).await, but is more ergonomic if you want to not take ownership of the handler.
Sourcepub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<SignalKind>
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<SignalKind>
Poll for a signal to be received. Does not require pinning the handler.