Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4995675
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2015-02-13 19:48:53


  1. # -*- coding: utf-8 -*-
  2. import sys, os, time, atexit
  3. from signal import SIGTERM
  4. class Daemon:
  5.     def __init__(self, pidfile, stderr='/data/deamon_err.log', stdout='/data/deamon_out.log', stdin='/dev/null'):
  6.         self.stdin = stdin
  7.         self.stdout = stdout
  8.         self.stderr = stderr
  9.         self.pidfile = pidfile

  10.     def _daemonize(self):
  11.         #脱离父进程
  12.         try:
  13.             pid = os.fork()
  14.             if pid > 0:
  15.                 sys.exit(0)
  16.         except OSError, e:
  17.             sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
  18.             sys.exit(1)

  19.         #脱离终端
  20.         os.setsid()
  21.         #修改当前工作目录
  22.         os.chdir("/")
  23.         #重设文件创建权限
  24.         os.umask(0)

  25.         #第二次fork,禁止进程重新打开控制终端
  26.         try:
  27.             pid = os.fork()
  28.             if pid > 0:
  29.                 sys.exit(0)
  30.         except OSError, e:
  31.             sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
  32.             sys.exit(1)

  33.         sys.stdout.flush()
  34.         sys.stderr.flush()
  35.         si = file(self.stdin, 'r')
  36.         so = file(self.stdout, 'a+')
  37.         se = file(self.stderr, 'a+', 0)
  38.         #重定向标准输入/输出/错误
  39.         os.dup2(si.fileno(), sys.stdin.fileno())
  40.         os.dup2(so.fileno(), sys.stdout.fileno())
  41.         os.dup2(se.fileno(), sys.stderr.fileno())

  42.         #注册程序退出时的函数,即删掉pid文件
  43.         atexit.register(self.delpid)
  44.         pid = str(os.getpid())
  45.         file(self.pidfile,'w+').write("%s\n" % pid)

  46.     def delpid(self):
  47.         os.remove(self.pidfile)
  48.     def start(self):
  49.         """
  50.         Start the daemon
  51.         """
  52.         # Check for a pidfile to see if the daemon already runs
  53.         try:
  54.             pf = file(self.pidfile,'r')
  55.             pid = int(pf.read().strip())
  56.             pf.close()
  57.         except IOError:
  58.             pid = None

  59.         if pid:
  60.             message = "pidfile %s already exist. Daemon already running?\n"
  61.             sys.stderr.write(message % self.pidfile)
  62.             sys.exit(1)

  63.         # Start the daemon
  64.         self._daemonize()
  65.         self._run()
  66.     def stop(self):
  67.         # Get the pid from the pidfile
  68.         try:
  69.             pf = file(self.pidfile,'r')
  70.             pid = int(pf.read().strip())
  71.             pf.close()
  72.         except IOError:
  73.             pid = None

  74.         if not pid:
  75.             message = "pidfile %s does not exist. Daemon not running?\n"
  76.             sys.stderr.write(message % self.pidfile)
  77.             return # not an error in a restart
  78.         # Try killing the daemon process
  79.         try:
  80.             while 1:
  81.                 os.kill(pid, SIGTERM)
  82.                 time.sleep(0.1)
  83.         except OSError, err:
  84.             err = str(err)
  85.             if err.find("No such process") > 0:
  86.                 if os.path.exists(self.pidfile):
  87.                     os.remove(self.pidfile)
  88.             else:
  89.                 print str(err)
  90.                 sys.exit(1)
  91.     def restart(self):
  92.         self.stop()
  93.         self.start()
  94.     def _run(self):

  95. class MyDaemon(Daemon):
  96.     def __init__(self, pidfile):
  97.         mod_daemon.Daemon.__init__(self,pidfile)
  98.         task_mgr_log = time.strftime('%Y%m%d') + '.log'
  99.         self.logger = mod_logger.logger(task_mgr_log)

  100.     def _run(self):
  101.             self.logger.debug("begin sleep")
  102.             time.sleep(20)
  103.             self.logger.debug("end sleep")


  104. if __name__ == "__main__":
  105.     daemon = MyDaemon('/tmp/daemon-example.pid')
  106.     if len(sys.argv) == 2:
  107.         if 'start' == sys.argv[1]:
  108.             print 'start daemon'
  109.             daemon.start()
  110.         elif 'stop' == sys.argv[1]:
  111.             print 'stop daemon'
  112.             daemon.stop()
  113.         elif 'restart' == sys.argv[1]:
  114.             print 'restart daemon'
  115.             daemon.restart()
  116.         else:
  117.             print "Unknown command"
  118.             sys.exit(2)
  119.         sys.exit(0)
  120.     else:
  121.         print "usage: %s start|stop|restart" % sys.argv[0]
  122.         sys.exit(2)

最上面是守护进程的基类,只需使自己的类继承这个基类,并重写_run(self)方法,就可以让这个守护进程跑起来。

这里需要注意几个地方:

1.因为守护进程是脱离了终端的,所以所有的stdout,stdin,stderr是不会输出到终端的,所以指定了stdout,stderr输出到日志文件。

2.自己的守护进程日志,需要在模块初始化的时候就一并初始化,而不能在_run方法的while循环中初始化,因为会导致日志句柄消耗过多,down掉程序。


原文链接


阅读(2030) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~