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.

#include <iostream>
#include <csignal>
#include <thread>
#include <atomic>

std::atomic<bool> quit(false);

void signal_handler(int signal) {
    std::cout << std::endl;
    std::cout << "Received signal: " << signal << std::endl;
    quit.store(true);
}

int main() {
    // Register the signal handler for SIGINT and SIGTERM
    std::signal(SIGINT, signal_handler);
    std::signal(SIGTERM, signal_handler);

    // This lambda function will run in a separate thread and wait for signals
    std::thread signal_thread([]() {
        while (!quit.load()) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    });

    std::cout << "Awaiting signal" << std::endl;
    
    // Wait for the signal thread to finish
    signal_thread.join();
    
    std::cout << "Exiting" << std::endl;
    return 0;
}

In this C++ version:

  1. We use the <csignal> library to handle signals, which is similar to Go’s os/signal package.

  2. Instead of channels, we use an std::atomic<bool> variable quit to communicate between threads.

  3. We define a signal_handler function that will be called when a signal is received. This function prints the signal and sets the quit flag to true.

  4. In the main function, we register our signal_handler for SIGINT and SIGTERM using std::signal.

  5. We create a separate thread using std::thread that continuously checks the quit flag. This is analogous to the goroutine in the Go version.

  6. 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.

$ g++ signals.cpp -std=c++11 -pthread -o signals
$ ./signals
Awaiting signal
^C
Received signal: 2
Exiting

This C++ implementation provides similar functionality to the Go version, demonstrating how to handle signals in a multi-threaded environment.