There is an alternative way to solve this problem, if you do not want your C extension (or ctypes DLL) to be bound to Python, for example, in the case when you want to create a C library with bindings in several languages, you must enable the C Extension to run for extended periods, and you can change the extension C:
Include the signal header in extension C.
#include <signal.h>
Create a typedef signal handler in extension C.
typedef void (*sighandler_t)(int);
Add signal handlers to the C extension, which will perform the actions necessary to interrupt any long-running code (set a stop flag, etc.) and save existing Python signal handlers.
sighandler_t old_sig_int_handler = signal(SIGINT, your_sig_handler); sighandler_t old_sig_term_handler = signal(SIGTERM, your_sig_handler);
Restore existing signal handlers every time the extension C. returns. This step ensures that Python signal handlers are reapplied.
signal(SIGINT, old_sig_int_handler); signal(SIGTERM, old_sig_term_handler);
If the long code is interrupted (flag, etc.), return a Python control with a return code indicating the signal number.
return SIGINT;
In Python, send the signal received in extension C.
import os import signal status = c_extension.run() if status in [signal.SIGINT, signal.SIGTERM]: os.kill(os.getpid(), status)
Python will do what you expect, such as raising KeyboardInterrupt for SIGINT.