How do I catch an Interrupt signal in Python when inside a blocking boost c++ method?
<p>I have a toolset which has been written in C++, and given Boost bindings for Python.</p>

<p>Initially, this code was all C++, and I caught a <kbd>CTRL</kbd>+<kbd>C</kbd> interrupt with:</p>

<pre><code>signal( SIGINT, signalCallbackHandler );
</code></pre>

<p>and</p>

<pre><code>void signalCallbackHandler(int /*signum*/)
{
    g_myObject-&gt;stop();
}
</code></pre>

<p>This worked fine.</p>

<p>However, now I've added the Python bindings in, I'm using Python to initialise the objects.</p>

<p>My initial thought was to do it like this:</p>

<pre><code>import signal

def handle_interrupt( signum, frame ) :
    g_myObject.stop()

signal.signal( signal.SIGINT, handle_interrupt )
g_myObject = MyObject()
g_myObject.start()
</code></pre>

<p>However, this signal handler is never called.</p>

<p>How should I be handling an interrupt like this? Do I need to do it inside C++, and then call the Python function from there?</p>

<p>Your python signal handler is not called because python defers execution of signal handlers until after the next bytecode instruction is to be executed - see <a href="https://docs.python.org/3.6/library/signal.html" rel="nofollow">the library documentation for signal</a>, section 18.8.1.1.</p>

<p>The reason for this is that a signal can arrive at any time, potentially half way through the execution of a python instruction. It would not be safe for the VM to begin executing the signal handler, because the VM is in an unknown state. Therefore, the actual signal handler installed by python merely sets a flag telling the VM to call the signal handler after the current instruction is complete.</p>

<p>If the signal arrives during execution of your C++ function, then the signal handler sets the flag and returns back to your C++ function.</p>

<p>If the main purpose of the signal handler is to allow the C++ function to be interrupted, then I suggestion you dispense with the python signal handler and install a C++ signal handler that sets a flag which triggers an early exit in your C++ code (presumably returning a value that indicates it was interrupted).</p>

<p>That approach would allow you to use the same code regardless of whether you are calling your code from python, C++ or perhaps another binding.</p>

python c++ boost