c-plus-plus
  1. c-plus-plus-signal-handling

C++ Signal Handling

Signal handling in C++ refers to the mechanism of handling unexpected or asynchronous events caused by the operating system or hardware. These events are called signals, and they can include things like interruptions from a keyboard or mouse, timeouts, or errors.

Syntax

#include <csignal>

void signal_handler(int signal) {
    // code
}

int main() {
    // register signal handler
    signal(SIGINT, signal_handler);
    
    // code
    return 0;
}

Here, we include the csignal header and define a signal handler function that takes an integer parameter representing the signal number. We then register the signal handler using the signal function, passing in the signal type we want to handle along with the function pointer to our handler function.

Example

#include <iostream>
#include <csignal>
#include <unistd.h>

using namespace std;

void signal_handler(int signum) {
    cout << "Interrupt signal (" << signum << ") received.\n";
    exit(signum);
}

int main() {
    // register signal handler
    signal(SIGINT, signal_handler);

    int i = 0;
    while (++i) {
        cout << "Sleeping...\n";
        if (i == 3) {
            raise(SIGINT);
        }
        sleep(1);
    }
    
    return 0;
}

Output

Sleeping...
Sleeping...
Sleeping...
Interrupt signal (2) received.

Explanation

In the above example, we have defined a signal handler function that simply prints out a message and exits when it is invoked. We then register this signal handler function to handle the SIGINT signal using the signal function.

In the main function, we enter an infinite loop, sleeping for one second every iteration. When the loop reaches the third iteration, we manually raise the SIGINT signal using the raise function. This triggers our signal handler function and prints out a message before exiting the program.

Use

Signal handling is used when we need to handle unexpected or asynchronous events in our programs. This can include things like abort signals, segmentation faults, timeouts, and more. By defining signal handler functions and registering them for specific signal types, we can gracefully handle these events and recover our program, even when they occur outside the normal control flow.

Important Points

  • Signal handling allows us to handle unexpected or asynchronous events in our programs.
  • We can define signal handler functions to handle specific signal types.
  • We register signal handler functions using the signal function.
  • Signals can be raised manually using the raise function.

Summary

Signal handling in C++ is an important mechanism for handling unexpected or asynchronous events in our programs. By defining signal handler functions and registering them for specific signal types, we can gracefully handle these events and recover our program, even when they occur outside the normal control flow.

Published on: