Ctrl-c i.e. KeyboardInterrupt to kill threads in p

2019-01-22 13:03发布

I read somewhere that KeyboardInterrupt exception is only read by the main thread in Python. I also read that the main thread is blocked while the child thread executes. So, does this mean that CTRL+ C can never reach to the child thread. I tried the following code:

def main():
    try:
        thread1.start() #thread is totally blocking e.g. while (1)
        thread1.join()
    except KeyboardInterrupt:
        print "Ctrl-c pressed ..."
        sys.exit(1)

In this case there is no effect of CTRL+C on the execution. It's like it is not able to listen to the interrupt. Am I understanding this the wrong way? Is there any other way to kill the thread using CTRL+C?

2条回答
聊天终结者
2楼-- · 2019-01-22 13:58

If you want to have main thread to receive the CTRL+C signal while joining, it can be done by adding timeout to join() call.

The following seems to be working (don't forget to add daemon=True if you want main to actually end):

thread1.start()
while True:
    thread1.join(600)
    if not thread1.isAlive():
        break
查看更多
倾城 Initia
3楼-- · 2019-01-22 14:02

The problem there is that you are using thread1.join(), which will cause your program to wait until that thread finishes to continue.

The signals will always be caught by the main process, because it's the one that receives the signals, it's the process that has threads.

Doing it as you show, you are basically running a 'normal' application, without thread features, as you start 1 thread and wait until it finishes to continue.

查看更多
登录 后发表回答