Mastering Signal Handling in C++: A Comprehensive Guide

Mastering Signal Handling in C++: A Comprehensive Guide

Signal handling in C++ is a critical mechanism that enables programs to respond effectively to specific events, known as signals, such as interruptions, illegal operations, or termination requests. This capability is essential for maintaining control over program behavior during unexpected situations.

Key Concepts

  • Signal: A notification sent to a process to inform it of an event. For instance, pressing Ctrl+C sends a SIGINT signal to terminate a program.
  • Signal Handling: The process of defining how a program should respond to a signal.

Common Signals

  • SIGINT: Interrupt from the keyboard (e.g., Ctrl+C).
  • SIGTERM: Termination request sent to the program.
  • SIGSEGV: Invalid memory access (segmentation fault).
  • SIGFPE: Floating-point exception (e.g., division by zero).

Signal Handling Functions

  1. signal(): Used to set a signal handler for a specific signal.
  2. sigaction(): A more advanced and preferred method for handling signals, offering greater control over signal handling behavior.

Basic Example

Below is a simple example demonstrating how to handle the SIGINT signal using the signal() function:

#include <iostream>
#include <csignal>
#include <cstdlib>

void signalHandler(int signal) {
    std::cout << "Interrupt signal (" << signal << ") received.\n";
    exit(signal);
}

int main() {
    // Register signal handler
    signal(SIGINT, signalHandler);

    while (true) {
        std::cout << "Running... Press Ctrl+C to stop.\n";
        sleep(1);
    }

    return 0;
}

Explanation of the Example:

  • signalHandler: This function is invoked when the SIGINT signal is received. It prints a message and exits the program.
  • main(): This function registers the signal handler for SIGINT and enters an infinite loop, simulating a running process.

Conclusion

Signal handling is a powerful feature in C++ that empowers programmers to manage and respond to various events during program execution. By utilizing signal() or sigaction(), developers can ensure that their applications behave correctly when confronted with unexpected conditions.