Forking a Daemon Process on Unix

来源:互联网 发布:怎么看淘宝的注册时间 编辑:程序博客网 时间:2024/06/06 11:35
Forking a Daemon Process on Unix

     Daemon processes must detach from their controlling terminal and process group. This is not hard, but it does take some care:

import sys, osdef main(  ):    """ An example daemon main routine; writes a datestamp to file        /tmp/daemon-log every 10 seconds.    """    import time    f = open("/tmp/daemon-log", "w")    while 1:        f.write('%s\n' % time.ctime(time.time(  )))        f.flush(  )        time.sleep(10)if _ _name_ _ == "_ _main_ _":    # Do the Unix double-fork magic; see Stevens's book "Advanced    # Programming in the UNIX Environment" (Addison-Wesley) for details    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 exiting            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(  )

0 0
原创粉丝点击