Signals in Rust
Here’s the translation of the Go code to Rust, with explanations in Markdown format suitable for Hugo:
Our first example demonstrates how to handle Unix signals in Rust. We’ll create a program that gracefully shuts down when it receives a SIGTERM
or stops processing input if it receives a SIGINT
. Here’s how to handle signals in Rust using channels.
Let’s break down the code:
We use the
signal_hook
crate to handle Unix signals in Rust.We create a channel using
mpsc::channel()
to communicate between the signal handling thread and the main thread.We create a
Signals
instance that will listen forSIGINT
andSIGTERM
.We spawn a new thread that will handle the signals. When a signal is received, it prints the signal and sends a message through the channel.
In the main thread, we wait for a message from the channel, which indicates that a signal has been received.
Once a signal is received, the program prints “Exiting” and terminates.
To run this program, you’ll need to add the signal-hook
dependency to your Cargo.toml
file:
When we run this program, it will block waiting for a signal. By typing ctrl-C
(which the terminal shows as ^C
), we can send a SIGINT
signal, causing the program to print the received signal and then exit.
This example demonstrates how to handle signals in Rust, allowing for graceful shutdown or other signal-specific behavior in your applications.