Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CTRL+C doesn't interrupt call to shared-library using CTYPES in Python

When calling a loop being performed in a C shared-library (dynamic library), Python will not receive a KeyboardInterrupt, and nothing will respond (or handle) CTRL+C.

What do I do?

like image 795
Dustin Oprea Avatar asked Jan 11 '13 04:01

Dustin Oprea


2 Answers

Unless you use PyDLL or PYFUNCTYPE; the GIL is released during the ctypes calls. Therefore the Python interpreter should handle SIGINT by raising KeyboardInterrupt in the main thread if the C code doesn't install its own signal handler.

To allow the Python code to run in the main thread; you could put the ctypes call into a 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)
like image 176
jfs Avatar answered Sep 20 '22 14:09

jfs


You will have to declare a signal handler for SIGINT, within the C, which is, hopefully, your project.

like image 35
Dustin Oprea Avatar answered Sep 20 '22 14:09

Dustin Oprea