C++ signal()

The signal() function in C++ sets the error handler for the specified signal.

signal() Prototype

void (*signal (int sig, void (*func)(int)))(int);

The signal function defines a method to handle the signal. The signal handler can be set so that one of the following action is performed:

  • Default handling of signal.
  • Ignore the signal.
  • User defined function is called to handle the signal.

It is defined in <csignal> header file.

signal() Parameters

  • sig: The signal to handle by the signal handler. It can take one of the following values:
    • SIGABRT
    • SIGFPE
    • SIGILL
    • SIGINT
    • SIGSEGV
    • SIGTERM
  • handler: The signal handler that handles the signal. It can be one of the following:
    • SIG_DFL: Default handling.
    • SIG_IGN: Ignore the signal.
    • Pointer to a function: User defined function to handle the signal. The signature of the function must be equivalent to the following:
      void fun(int sig);

signal() Return value

On success, it return previous signal handler and on failure SIG_ERR is returned.

Example: How signal() function works

#include <iostream>
#include <csignal>
 
using namespace std;

sig_atomic_t signalled = 0;

void handler(int sig)
{
    signalled = 1;
}

int main()
{
    signal(SIGINT, handler);
    
    raise(SIGINT);
    if (signalled)
        cout << "Signal is handled";
    else
        cout << "Signal is not handled";

    return 0;
}

When you run the program, the output will be:

Signal is handled

Check these related library functions as well: