2

I have a scenario where I want to handle SIGINT int python to clean up some things and then exit. I am using the following code.

import threading
import signal

def shutdown_handler(*args):
    raise SystemExit('Exiting')

signal.signal(signal.SIGINT, shutdown_handler)

def main():
    while 1:
        time.sleep(2)
        print("***")
    
sub_thread = threading.Thread(target=main)
sub_thread.start()
sub_thread.join()

But it requires me to press CTRL + c multiple times before the program exits. The following works fine

import time
import threading
import signal

def shutdown_handler(*args):
    # Do some clean up here. 
    raise SystemExit('Exiting')

signal.signal(signal.SIGINT, shutdown_handler)

def main():
    while 1:
        time.sleep(2)
        print("***")
    
main()

I am using the first code, because of a suggestion on this thread
Can you please tell me why this behaviour. Is it because of multiple threads running and how can I get around this? Thanks

3
  • 1
    Have a look at an alternative way to handle CTRL+C: stackoverflow.com/a/46346184/1012381 . Which OS and python versions are you running? Commented May 18, 2021 at 2:48
  • I am running Python 3.6.9 on Ubuntu 18.04.5 LTS Commented May 18, 2021 at 2:50
  • And a look at this link, appears you need to catch a KeyboardInterrupt exception: stackoverflow.com/a/2564161 Commented May 18, 2021 at 2:55

1 Answer 1

2

If terminating program with one Control-C is your only requirement, set daemon=True in constructor.

import threading
import signal

def shutdown_handler(*args):
    raise SystemExit('Exiting')

signal.signal(signal.SIGINT, shutdown_handler)

def main():
    while 1:
        time.sleep(2)
        print("***")
    
sub_thread = threading.Thread(target=main, daemon=True) # here
sub_thread.start()
sub_thread.join()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.