I am writing a python script that needs to run a thread which listens to a network socket.
I\'m having trouble with killing it using Ctrl+c usi
The issue is that after the execution falls off the main thread (after main()
returned), the threading
module will pause, waiting for the other threads to finish, using locks; and locks cannot be interrupted with signals. This is the case in Python 2.x at least.
One easy fix is to avoid falling off the main thread, by adding an infinite loop that calls some function that sleeps until some action is available, like select.select()
. If you don't need the main thread to do anything at all, use signal.pause()
. Example:
if __name__ == '__main__':
signal.signal(signal.SIGINT, handler)
main()
while True: # added
signal.pause() # added
It's because signals can only be caught by main thread. And here main thread ended his life long time ago (application is waiting for your thread to finish). Try adding
while True:
sleep(1)
to the end of your main()
(and of course from time import sleep
at the very top).
or as Kevin said:
for t in THREADS:
t.join(1) # join with timeout. Without timeout signal cannot be caught.