def daemonize(self):
        try:
            pid = os.fork()
            if pid > 0:
                # First parent; exit.
                sys.exit(0)
        except OSError as e:
            sys.stderr.write('Could not fork! %d (%s)\n' %
                             (e.errno, e.strerror))
            sys.exit(1)

        # Disconnect from parent environment.
        os.chdir('/')
        os.setsid()
        os.umask(0o022)

        # Fork again.
        try:
            pid = os.fork()
            if pid > 0:
                # Second parent; exit.
                sys.exit(0)
        except OSError as e:
            sys.stderr.write('Could not fork (2nd)! %d (%s)\n' %
                             (e.errno, e.strerror))
            sys.exit(1)

        # Redirect file descriptors.
        sys.stdout.flush()
        sys.stderr.flush()
        si = file(self.stdin, 'r')
        so = file(self.stdout, 'a+')
        se = file(self.stderr, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # Write the pidfile.
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as fp:
            fp.write('%s\n' % pid)
UNIX double-fork magic.
dataset/ETHPy150Open sivy/pystatsd/pystatsd/daemon.py/Daemon.daemonize