Signal processing and program exit for Python

Source: Internet
Author: User
Tags signal handler

if the written Python program is multithreaded or multi-process, it involves the issue of program security exit.
one, multi-process program exitthe child process needs to be killed one after the other before exiting the main process, or it will cause the main process to exit (CTRL + C) After the child process does not exit and continue to run.
?
Ii. exit of multi-threadedYou need to set the thread's "Daemon" property to "True" (The default is "False") when multiple threads are started .
otherwise the program will deadlock and cannot exit (CTRL + C);

Here is the sample code:
Import Signal
Import Threading

def Sig_handler (SIG, frame):
Try:
th_timeout.stop ()
Th_timeout.join ()
except Exception, ex:
exit (0)
?
def main ():
    ... 
# #set Signal Handler
signal.signal (signal. SIGTERM, Sig_handler)
signal.signal (signal. SIGINT, Sig_handler)

Global Th_timeout
th_timeout = Threading. Thread (Target=your_application, args= ())
Th_timeout.setdaemon (' True ')
Th_timeout.start ()

if __name__ = = "__main__":
Main ()
?

Signal processing and program exit for Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.