python从线程结束主进程的例子

来源:互联网 发布:c 软件开发视频教程 编辑:程序博客网 时间:2024/06/01 08:40

     试验了一下从python的一个线程中来结束主进程的方法, sys.exit()只能结束线程,无法结束主进程。 而os._exit()却可以做到。

下面是具体的程序;

#------------------------------------   self_monitor.py  --------------------------------

#!/usr/bin/env python
import threading
import sys,os
import subprocess
from time import sleep

Ncount=0
token_exit=False

def daemon():
   global Ncount
   while True:
        sleep(0.1)
        Ncount+=1
        print 'From daemon ----'

def self_monitor():
   global Ncount
   global token_exit
   try:
     while True:
        sleep(2)
        print 'From self_monitor: Ncount=',Ncount
        if token_exit:
             print 'token_exit = True, try to start a new python instance ...'
             subprocess.Popen("/home/fa/self_monitor.py") #-- NONBLOCKING
             break

     #sys.exit(0) #-- sys.exit(0) kill subprocess only, can't kill main
     print 'Try to end current python instance, executing os._exit(0).....'
     os._exit(0) #-- os._exit CAN kill main process
   except Exception, err:
       print err
       raise

def main():
   global Ncount
   global token_exit
   t1=threading.Thread(target=self_monitor,args=())
   t1.setDaemon(False)  #---- use Fale to set as daemon
   t2=threading.Thread(target=daemon,args=())
   t2.setDaemon(False)  #---- use Fale to set as daemon
   t1.start()
   t2.start()
   sleep(1)

   token_exit=True  #---= set exit token.
   while True:
        sleep(2)
        print '---- from MAIN -----'

if __name__ == '__main__':
   main()

原创粉丝点击