#!/usr/bin/env python # # based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 import os, pwd, grp def daemonize(euid = None, egid = None): """Detach a process from the controlling terminal, change euid/egid and run it in the background as a daemon. """ try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): os.setsid() try: pid = os.fork() except OSError, e: raise Exception, "%s [%d]" % (e.strerror, e.errno) if (pid == 0): os.chdir('/') os.umask(0) else: os._exit(0) else: os._exit(0) for fd in range(0, 2): os.close(fd) os.open(os.devnull, os.O_RDONLY) # fd0 stdin os.open(os.devnull, os.O_WRONLY) # fd1 sdtout os.dup2(1, 2) # fd2 stderr if euid: os.seteuid(pwd.getpwnam(euid)[2]) if egid: os.setegid(grp.getgrnam(egid)[2])