python写的linux平台双守护进程

来源:互联网 发布:回收站的数据恢复软件 编辑:程序博客网 时间:2024/05/21 19:26
# -*- coding: utf-8 -*-import multiprocessingimport osimport timeimport sysimport fcntlimport threadingimport socket# Global defs.DEBUG =1# Function defs.def err(func,error,exc=''):    #print  >> sys.stderr,time.strftime('-%X-', time.localtime()),'[',func,']',error,'.',exc    passUMASK = 0WORKDIR = "/"MAXFD = 1024if (hasattr(os, "devnull")):   REDIRECT_TO = os.devnullelse:   REDIRECT_TO = "/dev/null"def createDaemon():   try:      pid = os.fork()   except OSError, e:      raise Exception, "%s [%d]" % (e.strerror, e.errno)   if (pid == 0):# The first child.      os.setsid()      try:         pid = os.fork()# Fork a second child.      except OSError, e:         raise Exception, "%s [%d]" % (e.strerror, e.errno)      if (pid == 0):# The second child.         os.chdir(WORKDIR)         os.umask(UMASK)      else:         os._exit(0)# Exit parent (the first child) of the second child.   else:      os._exit(0)# Exit parent of the first child.   import resource# Resource usage information.   maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]   if (maxfd == resource.RLIM_INFINITY):      maxfd = MAXFD     os.open(REDIRECT_TO, os.O_RDWR)# standard input (0)   # Duplicate standard input to standard output and standard error.   os.dup2(0, 1)# standard output (1)   os.dup2(0, 2)# standard error (2)   return(0)def LsnrWatcher(second):    if DEBUG:        err(sys._getframe().f_code.co_name,'LsnrWatcher started.pid='+str(os.getpid())+',ppid='+str(os.getppid()))        while True:        s =None        try:            s =second.recv(1)        except:            pass        try:            second.close()        except:            pass                    if DEBUG:            err(sys._getframe().f_code.co_name,'recv returned')        (first,second) =socket.socketpair()        if(os.fork()==0):            createDaemon()            second.close()            Lsnr(first)            os._exit(0)        first.close()def LsnrThread(first):    while True:        s =None        try:            s =first.recv(1)        except:            pass        try:            first.close()        except:            pass                   if DEBUG:            err(sys._getframe().f_code.co_name,'recv returned')        (first,second) =socket.socketpair()        if(os.fork()==0):            createDaemon()            first.close()            LsnrWatcher(second)            os._exit(0)        second.close()def Lsnr(first):    if DEBUG:        err(sys._getframe().f_code.co_name,'Lsnr started.pid='+str(os.getpid())+',ppid='+str(os.getppid()))    th =threading.Thread(target=LsnrThread,args=(first,))    th.daemon =False    th.start()    for i in range(60):        time.sleep(2)        err( sys._getframe().f_code.co_name,'  '+str(i)+' pid='+str(os.getpid()) )def StartLsnr():    (first,second) =socket.socketpair()    if(os.fork()==0):        createDaemon()        second.close()        Lsnr(first)        os._exit(0)    if(os.fork()==0):        createDaemon()        first.close()        LsnrWatcher(second)        os._exit(0)    first.close()    second.close()def RunMain():    if DEBUG:        err(sys._getframe().f_code.co_name,'pid='+str(os.getpid())+',ppid='+str(os.getppid()))    StartLsnr()    time.sleep(300)if __name__ == '__main__':    createDaemon()    RunMain()


Watch进程负责守护Lsnr及其它工作进程组,而Watch由Lsnr守护。
杀Lsnr后,由Watch来启动Lsnr,  杀Watch由Lsnr来启动Watch,  杀工作组中的进程由Watch来启动。

 

 

转自:http://blog.csdn.net/dungeonsnd/article/details/6701009

原创粉丝点击