Python program with thread can't catch CTRL+C

后端 未结 2 1224
刺人心
刺人心 2020-12-17 22:40

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

相关标签:
2条回答
  • 2020-12-17 23:04

    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
    
    0 讨论(0)
  • 2020-12-17 23:09

    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.
    
    0 讨论(0)
提交回复
热议问题