Liuw's Thinkpad

想要赢就先学会输,想要成功就先学会失败

Archive for the ‘session’ tag

Python Daemonize

without comments

Code copied from Xen.

def daemonize():
    # Detach from TTY

    # Become the group leader (already a child process)
    os.setsid()

    # Fork, this allows the group leader to exit,
    # which means the child can never again regain control of the
    # terminal
    if os.fork():
        os._exit(0)

    # Detach from standard file descriptors, and redirect them to
    # /dev/null or the log as appropriate.
    # We open the log file first, so that we can diagnose a failure to do
    # so _before_ we close stderr
    try:
        parent = os.path.dirname(XEND_DEBUG_LOG)
        mkdir.parents(parent, stat.S_IRWXU)
        fd = os.open(XEND_DEBUG_LOG, os.O_WRONLY|os.O_CREAT|os.O_APPEND, 0666)
    except Exception, exn:
        print >>sys.stderr, exn
        print >>sys.stderr, ("Xend failed to open %s. Exiting!" %
                             XEND_DEBUG_LOG)
        sys.exit(1)

    os.close(0)
    os.close(1)
    os.close(2)
    if XEND_DEBUG:
        os.open('/dev/null', os.O_RDONLY)
        os.dup(fd)
        os.dup(fd)
    else:
        os.open('/dev/null', os.O_RDWR)
        os.dup(0)
        os.dup(fd)
    os.close(fd)

    print >>sys.stderr, ("Xend started at %s." %
                         time.asctime(time.localtime()))

See more about Process Group from Wiki.

A note from ‘man 2 setsid’

A child created via fork(2) inherits its parent’s session ID. The ssession ID is preserved across an execve(2).

A process group leader is a process with process group ID equal to its PID. In order to be sure that setsid() will succeed, fork(2) and _exit(2), and have the child do setsid().

Written by liuw

March 24th, 2010 at 10:34 pm