'do the UNIX double-fork magic, see Stevens\' "Advanced
Programming in the UNIX Environment" for details (ISBN 0201563177)
http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16'

def daemonize(self):

    try:
        pid = os.fork()
        if (pid > 0):
            sys.exit(0)
    except OSError as e:
        sys.stderr.write(('fork    #1    failed:    %d    (%s)\n' % (e.errno, e.strerror)))
        sys.exit(1)
    os.chdir('/')
    os.setsid()
    os.umask(0)
    try:
        pid = os.fork()
        if (pid > 0):
            sys.exit(0)
    except OSError as e:
        sys.stderr.write(('fork    #2    failed:    %d    (%s)\n' % (e.errno, e.strerror)))
        sys.exit(1)
    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())
    atexit.register(self.delpid)
    pid = str(os.getpid())
    file(self.pidfile, 'w+').write(('%s\n' % pid))
