Catch CTRL+C Event on Linux using C++

Catch CTRL+C Event on Linux using C++

In the realm of Linux programming, catching signals like SIGINT (CTRL+C) is crucial for gracefully handling user interruptions. When a user presses CTRL+C, the operating system sends a SIGINT signal to the process, indicating a request for termination. By catching this signal, we can perform cleanup tasks or implement custom behavior before exiting the program abruptly. This tutorial demonstrates how to catch CTRL+C event on Linux using C++.

The provided code sets up a signal handler function to catch the SIGINT signal, which is generated when the user presses CTRL+C. The handler function simply prints the signal number and then exits the program with the received signal.

In the main function, a sigaction structure is initialized to specify the handler function for SIGINT. The structure's sa_mask is cleared to ensure no additional signals are blocked during handling, and sa_flags is set to 0 for default behavior. Finally, the sigaction function registers the handler with the SIGINT signal. The program then enters a pause state, waiting indefinitely until a signal is received.

#include <iostream>
#include <csignal>

void handler(int signal){
    std::cout << "Caught signal: " << signal << std::endl;
    exit(signal);
}

int main()
{
    struct sigaction sigIntAction{};
    sigIntAction.sa_handler = handler;
    sigemptyset(&sigIntAction.sa_mask);
    sigIntAction.sa_flags = 0;
    sigaction(SIGINT, &sigIntAction, nullptr);

    pause();

    return 0;
}

Output:

Caught signal: 2

Leave a Comment

Cancel reply

Your email address will not be published.