Okay, let's break down how to safely handle SIGINT (Ctrl+C) and translate it into a C++ exception in Linux.
The critical point is: You cannot safely throw a C++ exception directly from a signal handler.
Signal handlers are asynchronous and can interrupt your program at almost any point. The C++ exception handling mechanism (stack unwinding, calling destructors, etc.) is not designed to be async-signal-safe. Doing so leads to undefined behavior, which most often results in a crash or corrupted program state.
The safe pattern involves setting a flag in the signal handler and then checking that flag in your main program loop (or other appropriate places) to decide when and where to throw the exception.
Here's the standard and recommended approach:
Use sigaction: It's the POSIX standard and more robust than signal().
Set an Atomic Flag: Use std::atomic<bool> (or a volatile sig_atomic_t in C style) to communicate between the signal handler and the rest of the program. Atomic operations are generally safe in signal handlers (though sig_atomic_t is the only type guaranteed by C standards; std::atomic<bool> is usually implemented safely on modern systems).
Check the Flag: Periodically check the flag in your main code.
Handle EINTR: If your program uses blocking system calls (like read, write, sleep, wait, poll, epoll_wait, etc.), a signal handler will typically interrupt these calls. They will return -1 and set errno to EINTR. You must check for EINTR after blocking calls and combine this with checking your flag.
Throw Outside the Handler: If the flag is set (and potentially errno == EINTR), then you can throw your exception from the safe context of your main code.
Let's illustrate with code:
cpp
#include <iostream>
#include <csignal>
#include <atomic>
#include <unistd.h> // For sleep and checking EINTR
#include <cerrno> // For errno
#include <system_error> // For std::system_error (useful for EINTR)
// 1. Declare an atomic flag
std::atomic<bool> sigint_received(false);
// Define a custom exception type for clarity
class SignalException : public std::runtime_error {
public:
SignalException(int sig_num) : std::runtime_error("Received signal " + std::to_string(sig_num)), signal_number(sig_num) {}
int signal_number;
};
// 2. The signal handler function
// IMPORTANT: This function must be async-signal-safe.
// Only a very limited set of functions are safe to call inside a signal handler.
// Setting an atomic variable is generally safe.
void signal_handler(int signal) {
if (signal == SIGINT) {
sigint_received.store(true);
// Do NOT throw here! Do NOT use iostream, new/delete, malloc/free, mutexes, etc.
// A safe print could potentially be done using write() to stderr,
// but it's best to keep handlers minimal.
}
}
// Helper function to set up the signal handler
void setup_signal_handler() {
struct sigaction sa;
// Use the handler function
sa.sa_handler = signal_handler;
// Block all signals during the execution of the handler (optional but common)
sigemptyset(&sa.sa_mask);
// SA_RESTART: If set, interrupted system calls are automatically restarted.
// We usually *don't* want SA_RESTART for SIGINT if we are checking EINTR
// to unblock calls like read/sleep. So we typically don't set it or explicitly clear.
sa.sa_flags = 0; // Clear SA_RESTART and other flags
if (sigaction(SIGINT, &sa, nullptr) == -1) {
// Handle error
std::cerr << "Error setting up signal handler: " << strerror(errno) << std::endl;
exit(EXIT_FAILURE);
}
}
// Example function that does work and checks the flag/EINTR
void do_some_work_that_can_be_interrupted() {
std::cout << "Working..." << std::endl;
// Example: A loop that could be interrupted
for (int i = 0; i < 10; ++i) {
// 3. Check the flag periodically
if (sigint_received.load()) {
std::cout << "Signal received during work." << std::endl;
throw SignalException(SIGINT);
}
// Example of a blocking call that can be interrupted by SIGINT
// sleep() might return early if interrupted, setting errno to EINTR
std::cout << "Sleeping (can be interrupted)..." << std::endl;
if (sleep(1) == -1) {
// Check if the interruption was due to a signal
if (errno == EINTR) {
std::cout << "Sleep interrupted by signal." << std::endl;
// Even if sleep was interrupted, we still check the flag
// to confirm it was *our* SIGINT handler that ran.
if (sigint_received.load()) {
throw SignalException(SIGINT);
} else {
// Handle other reasons for EINTR if necessary, or just continue
// if it was a signal we don't care about throwing for.
std::cerr << "Warning: Interrupted by unexpected signal/EINTR without sigint_received set?" << std::endl;
// You might want to re-sleep for the remaining time or just break/continue
}
} else {
// Handle other sleep errors
throw std::system_error(errno, std::system_category(), "sleep failed");
}
}
std::cout << "Woke up." << std::endl;
}
std::cout << "Work finished." << std::endl;
}
int main() {
setup_signal_handler();
std::cout << "Press Ctrl+C to trigger SIGINT." << std::endl;
try {
// This is where your main program logic goes.
// It should check the flag at appropriate points.
do_some_work_that_can_be_interrupted();
// Example: If your program blocks on I/O
// char buffer[256];
// std::cout << "Enter something (or Ctrl+C): ";
// if (read(STDIN_FILENO, buffer, sizeof(buffer)) == -1) {
// if (errno == EINTR) {
// std::cout << "Read interrupted by signal." << std::endl;
// if (sigint_received.load()) {
// throw SignalException(SIGINT);
// }
// } else {
// throw std::system_error(errno, std::system_category(), "read failed");
// }
// } else {
// // Process input
// }
// If the program finishes without receiving SIGINT
std::cout << "Program finished normally." << std::endl;
} catch (const SignalException& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
// Perform cleanup here as needed
return EXIT_FAILURE; // Indicate failure due to signal
} catch (const std::exception& e) {
std::cerr << "Caught standard exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Explanation:
std::atomic<bool> sigint_received(false);: A flag visible to both the signal handler and main. std::atomic ensures that reads and writes to this flag are thread-safe and signal-safe on most modern platforms.
signal_handler(int signal): This function is called asynchronously by the OS when SIGINT occurs. Its only job is to set the sigint_received flag. It strictly avoids any non-async-signal-safe operations (like std::cout, new, etc.).
setup_signal_handler(): Configures the operating system to call signal_handler when SIGINT is delivered to the process.
sigaction is used instead of the older signal().
sa.sa_handler = signal_handler; sets the function to be called.
sigemptyset(&sa.sa_mask); ensures no other signals are blocked while the handler runs (can be changed if needed).
sa.sa_flags = 0; is crucial. By default or with SA_RESTART, system calls interrupted by the signal handler might be automatically restarted by the kernel. By clearing SA_RESTART, interrupted system calls like sleep, read, write, poll, etc., will return -1 and set errno to EINTR. This allows your main loop to detect that an interruption occurred.
Checking the Flag (sigint_received.load()): Your main code (e.g., inside loops, before/after blocking calls) checks the state of this flag using .load().
Handling EINTR: After any system call that might block and return EINTR (because SA_RESTART was not set), you must check if the return value was -1 and errno is EINTR.
Throwing the Exception: If the flag is set (or errno == EINTR followed by checking the flag), you then throw your exception from the safe context of your main function or other application logic.
try-catch: Wrap the main logic that can potentially be interrupted in a try block to catch the SignalException. This allows for controlled cleanup and graceful shutdown.
This pattern correctly separates the asynchronous signal handling (minimal, safe actions) from the synchronous exception throwing (part of your normal program flow).