免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3869 | 回复: 1
打印 上一主题 下一主题

[Python]一个简单的守护进程 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-09-21 20:40 |只看该作者 |倒序浏览

                                                                import os
import sys
def create_daemon():
        pid = os.fork()  
  if pid == 0:
    os.setsid()
    if pid == 0:
      os.chdir('/usr/python/daemon')
      os.umask(0)  
    else:
      os._exit(0)
  else:
    os._exit(0)
if __name__ == "__main__"
  create_daemon()
    ...               
               
               
               
               
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/43271/showart_387216.html

论坛徽章:
0
2 [报告]
发表于 2008-08-06 13:33 |只看该作者

  1. '''
  2.     This module is used to fork the current process into a daemon.
  3.     Almost none of this is necessary (or advisable) if your daemon
  4.     is being started by inetd. In that case, stdin, stdout and stderr are
  5.     all set up for you to refer to the network connection, and the fork()s
  6.     and session manipulation should not be done (to avoid confusing inetd).
  7.     Only the chdir() and umask() steps remain as useful.
  8.     References:
  9.         UNIX Programming FAQ
  10.             1.7 How do I get my program to act like a daemon?
  11.                 [url]http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16[/url]
  12.         Advanced Programming in the Unix Environment
  13.             W. Richard Stevens, 1992, Addison-Wesley, ISBN 0-201-56317-7.

  14.     History:
  15.       2001/07/10 by Juergen Hermann
  16.       2002/08/28 by Noah Spurrier
  17.       2003/02/24 by Clark Evans
  18.       2003/11/01 by Irmen de Jong --- adapted a bit for Snakelets
  19.                                     (raises exception at certain points)
  20.       
  21.       [url]http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012[/url]
  22. '''
  23. import sys, os, time
  24. from signal import SIGINT,SIGTERM,SIGKILL

  25. def daemonize(stdout='/dev/null', stderr=None, stdin='/dev/null',
  26.               pidfile=None, startmsg = 'started with pid %s' ):
  27.     '''
  28.         This forks the current process into a daemon.
  29.         The stdin, stdout, and stderr arguments are file names that
  30.         will be opened and be used to replace the standard file descriptors
  31.         in sys.stdin, sys.stdout, and sys.stderr.
  32.         These arguments are optional and default to /dev/null.
  33.         Note that stderr is opened unbuffered, so
  34.         if it shares a file with stdout then interleaved output
  35.         may not appear in the order that you expect.
  36.     '''

  37.     # flush io
  38.     sys.stdout.flush()
  39.     sys.stderr.flush()

  40.     # Do first fork.
  41.     try:
  42.         pid = os.fork()
  43.         if pid > 0: sys.exit(0) # Exit first parent.
  44.     except OSError, e:
  45.         sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
  46.         sys.exit(1)
  47.         
  48.     # Decouple from parent environment.
  49.     os.chdir("/")
  50.     os.umask(0)
  51.     os.setsid()
  52.    
  53.     # Do second fork.
  54.     try:
  55.         pid = os.fork()
  56.         if pid > 0: sys.exit(0) # Exit second parent.
  57.     except OSError, e:
  58.         sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
  59.         sys.exit(1)
  60.    
  61.     # Open file descriptors and print start message
  62.     if not stderr: stderr = stdout
  63.     si = file(stdin, 'r')
  64.     so = file(stdout, 'a+')
  65.     se = file(stderr, 'a+', 0)  #unbuffered
  66.     pid = str(os.getpid())
  67.     sys.stderr.write("\n%s\n" % startmsg % pid)
  68.     sys.stderr.flush()
  69.     if pidfile: file(pidfile,'w+').write("%s\n" % pid)
  70.    
  71.     # Redirect standard file descriptors.
  72.     os.dup2(si.fileno(), sys.stdin.fileno())
  73.     os.dup2(so.fileno(), sys.stdout.fileno())
  74.     os.dup2(se.fileno(), sys.stderr.fileno())


  75. class DaemonizeError(Exception): pass


  76. def startstop(stdout='/dev/null', stderr=None, stdin='/dev/null',
  77.               pidfile='pid.txt', startmsg = 'started with pid %s', action=None ):
  78.               
  79.     if not action and len(sys.argv) > 1:
  80.         action = sys.argv[1]

  81.     if action:
  82.         try:
  83.             pf  = file(pidfile,'r')
  84.             pid = int(pf.read().strip())
  85.             pf.close()
  86.         except IOError:
  87.             pid = None
  88.         if 'stop' == action or 'restart' == action:
  89.             if not pid:
  90.                 mess = "Could not stop, pid file '%s' missing.\n"
  91.                 raise DaemonizeError(mess % pidfile)
  92.             try:
  93.                while 1:
  94.                    print "sending SIGINT to",pid
  95.                    os.kill(pid,SIGINT)
  96.                    time.sleep(2)
  97.                    print "sending SIGTERM to",pid
  98.                    os.kill(pid,SIGTERM)
  99.                    time.sleep(2)
  100.                    print "sending SIGKILL to",pid
  101.                    os.kill(pid,SIGKILL)
  102.                    time.sleep(1)
  103.             except OSError, err:
  104.                print "process has been terminated."
  105.                os.remove(pidfile)
  106.                if 'stop' == action:
  107.                    return    ## sys.exit(0)
  108.                action = 'start'
  109.                pid = None
  110.         if 'start' == action:
  111.             if pid:
  112.                 mess = "Start aborted since pid file '%s' exists. Server still running?\n"
  113.                 raise DaemonizeError(mess % pidfile)
  114.             daemonize(stdout,stderr,stdin,pidfile,startmsg)
  115.             return
  116.     print "usage: %s start|stop|restart" % sys.argv[0]
  117.     raise DaemonizeError("invalid command")

  118. def test():
  119.     '''
  120.         This is an example main function run by the daemon.
  121.         This prints a count and timestamp once per second.
  122.     '''
  123.     sys.stdout.write ('Message to stdout...')
  124.     sys.stderr.write ('Message to stderr...')
  125.     c = 0
  126.     while 1:
  127.         sys.stdout.write ('%d: %s\n' % (c, time.ctime(time.time())) )
  128.         sys.stdout.flush()
  129.         c = c + 1
  130.         time.sleep(1)

  131. if __name__ == "__main__":
  132.     startstop(stdout='/tmp/daemonize.log',
  133.               pidfile='/tmp/daemonize.pid')
  134.     if sys.argv[1]in ('start', 'restart'):
  135.         test()
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP