Signals in C++
Here’s the translation of the Go code to C++ with explanations in Markdown format suitable for Hugo:
Our program demonstrates how to handle Unix signals in C++. For example, we might want a server to gracefully shutdown when it receives a SIGTERM
, or a command-line tool to stop processing input if it receives a SIGINT
. Here’s how to handle signals in C++ using the <csignal>
library.
In this C++ version:
We use the
<csignal>
library to handle signals, which is similar to Go’sos/signal
package.Instead of channels, we use an
std::atomic<bool>
variablequit
to communicate between threads.We define a
signal_handler
function that will be called when a signal is received. This function prints the signal and sets thequit
flag to true.In the
main
function, we register oursignal_handler
forSIGINT
andSIGTERM
usingstd::signal
.We create a separate thread using
std::thread
that continuously checks thequit
flag. This is analogous to the goroutine in the Go version.The main thread waits for the signal thread to finish by calling
join()
on the thread object.
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 signal number and then exit.
This C++ implementation provides similar functionality to the Go version, demonstrating how to handle signals in a multi-threaded environment.