CTRL + C does not interrupt a call to a shared library using CTYPES in Python

When you call a loop that runs in the C shared library (dynamic library), Python will not receive KeyboardInterrupt, and nothing will respond (or process) CTRL + C.

What should I do?

+6
source share
3 answers

If you are not using PyDLL or PYFUNCTYPE ; GIL is freed during ctypes calls. Therefore, the Python interpreter must process SIGINT by raising KeyboardInterrupt in the main thread if the C code does not set its own signal handler.

To allow Python code to run in the main thread; you can put the ctypes call in the background thread:

 import threading t = threading.Thread(target=ctypes_call, args=[arg1, arg2, ...]) t.daemon = True t.start() while t.is_alive(): # wait for the thread to exit t.join(.1) 
+3
source

You will need to declare a signal handler for SIGINT in C, which I hope will be your project.

+1
source

I used a threaded solution, but then switched to a signal one. The work I use is to send SIGTERM from the SIGINT handler, for example:

 signal.signal(signal.SIGINT, lambda s, f : os.kill(os.getpid(), signal.SIGTERM)) 

Here I just want to keep the main idea of ​​the solution so that I can find it faster next time and the reason why I changed the approach. The threaded option is not suitable for me, because OpenMP gets much slower when it is called not from the main thread.

+1
source

All Articles