Daemonize?

A.M. Kuchling amk at amk.ca
Sat Sep 7 14:43:51 CEST 2002


In article <mailman.1031184848.32071.python-list at python.org>, 
   Richard Jones wrote:
> Note you can also just assign an object with a write() method that does 
> nothing to sys.std(out|err) and a similar object to sys.stdin. Why the second 
> fork, btw?

No, reassigning sys.stdin and stdout isn't sufficient; you really,
truly have to close those file descriptors.  This is complicated
slightly by the fact that Python's .close() method for
stdin/stdout/stderr doesn't actually do anything.

The second fork ensures that the parent PID of your daemon process is
1.  I think it also ensures that the daemon is in a process group of
its own.

Here's the daemonize function I use; I think Greg Ward originally
gave it to me.

    def daemonize (self):
        # Fork once
        if os.fork() != 0:
            os._exit(0)
        os.setsid()                     # Create new session
        if os.fork() != 0:      
            os._exit(0)         
        os.chdir("/")         
        os.umask(0)

        os.close(sys.__stdin__.fileno())
        os.close(sys.__stdout__.fileno())
        os.close(sys.__stderr__.fileno())
        
--amk



More information about the Python-list mailing list