Search code examples
c++macossignals

Unable to use signal handling


I have been trying to experiment with signals in C++ and didn't have much luck so far.

I am working on a MacBook Pro M2, 2022 with XCode 14.3.1 and I have tried to replicate the example from the std::signal cppreference page (link: https://en.cppreference.com/w/cpp/utility/program/signal) shown below

#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';
}

The result should be

SignalValue: 0
Sending signal: 2
SignalValue: 2

which is verified both on cppreference page (running the example) as well as "Compiler Explorer" with x86-64 clang 16.0.0, x86-64 clang 15.0.0 and x86-64 clang 14.0.0, x86-64 clang (trunk), x86-64 gcc (trunk), x86-64 gcc 13.2 and x86-64 gcc 12.3 (just to make sure it is working "in general").

The exact same code gives the following results in the configuration I have

SignalValue: 0
Sending signal: 2
SignalValue: 0

It seems that the signal_handler function is never called and the behaviour is the same in Debug (-O0) and Release (-O3 and -Os). I have absolutely no idea why this is happening, so any help would be appreciated.


Solution

  • You are invoking the test program under an IDE that is blocking SIGINT, and the signal mask is inherited by its children (copied over a fork() of course, and then preserved across an execve()).

    Try invoking the executable from a plain interactive shell, and you should see the expected behavior. Alternately, try SIGUSR1, which is rarely blocked by things like IDEs.