std::signal

Header: <csignal>

Changes handling of the signal sig. Depending on handler, the signal can be ignored, set to default, or handled by a user-defined function.

# Declarations

/* signal-handler */* signal( int sig, /* signal-handler */* handler );
extern "C" using /* signal-handler */ = void(int);

(exposition only*)

# Parameters

# Return value

Previous signal handler on success or SIG_ERR on failure (setting a signal handler can be disabled on some implementations).

# Notes

POSIX requires that signal is thread-safe, and specifies a list of async-signal-safe library functions that may be called from any signal handler.

Signal handlers are expected to have C linkage and, in general, only use the features from the common subset of C and C++. However, common implementations allow a function with C++ linkage to be used as a signal handler.

# Example

#include <csignal>
#include <iostream>
 
namespace
{
    volatile std::sig_atomic_t gSignalStatus;
}
 
void signal_handler(int signal)
{
    gSignalStatus = signal;
}
 
int main()
{
    // Install a signal handler
    std::signal(SIGINT, signal_handler);
 
    std::cout << "SignalValue: " << gSignalStatus << '\n';
    std::cout << "Sending signal: " << SIGINT << '\n';
    std::raise(SIGINT);
    std::cout << "SignalValue: " << gSignalStatus << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 3756C++17it was unclear whether std::atomic_flag is signal-safeit is

# See also