Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a child thread with Ctrl+C?

Tags:

I would like to stop the execution of a process with Ctrl+C in Python. But I have read somewhere that KeyboardInterrupt exceptions are only raised in the main thread. I have also read that the main thread is blocked while the child thread executes. So how can I kill the child thread?

For instance, Ctrl+C has no effect with the following code:

def main():     try:         thread = threading.Thread(target=f)         thread.start()  # thread is totally blocking (e.g. while True)         thread.join()     except KeyboardInterrupt:         print "Ctrl+C pressed..."         sys.exit(1)  def f():     while True:         pass  # do the actual work 
like image 781
Amit S Avatar asked Nov 09 '10 17:11

Amit S


2 Answers

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 
like image 188
korc Avatar answered Dec 06 '22 16:12

korc


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.

like image 35
webbi Avatar answered Dec 06 '22 17:12

webbi