Python 守护进程【转】

#!/usr/bin/python
import sys, os
def main():
   """
   A demo deamon main routine, write a datestamp to
   /tmp/deamon-log every 10 seconds.
   """

   import time
   f = open("/tmp/deamon-log", "w")
   while True:
      f.write('%s\n' % time.ctime(time.time()))
      f.flush()
      time.sleep(10)
if __name__ == "__main__":
# do the UNIX double-fork magic, see Stevens' "Advanced
# Programming in the UNIX Environment" for details(ISBN 0201563177)
   try:
      pid = os.fork()
      if pid > 0:
# exit first parent
         sys.exit(0)
   except OSError, e:
      print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
      sys.exit(1)
# decouple from parent environment
   os.chdir("/")
   os.setsid()
   os.umask(0)

# do second fork
   try:
      pid = os.fork()
      if pid > 0:
# exit from second parent, print eventual PID before
         print "Daemon PID %d" % pid
         sys.exit(0)
   except OSError, e:
      print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
      sys.exit(1)
# start the daemon main loop
   main()

原文:http://www.cnblogs.com/lichkingct/archive/2010/08/27/1810470.html

原文:http://code.activestate.com/recipes/66012/

posted @ 2012-11-28 20:18  Leo Forest  阅读(204)  评论(0编辑  收藏  举报