python写的linux平台双守护进程

26 篇文章 0 订阅
# -*- coding: utf-8 -*-
import multiprocessing
import os
import time
import sys
import fcntl
import threading
import socket


# Global defs.
DEBUG =1


# Function defs.
def err(func,error,exc=''):
    #print  >> sys.stderr,time.strftime('-%X-', time.localtime()),'[',func,']',error,'.',exc
    pass
UMASK = 0
WORKDIR = "/"
MAXFD = 1024
if (hasattr(os, "devnull")):
   REDIRECT_TO = os.devnull
else:
   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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值