'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:
        msg = ('fork    #1    failed:    %d    (%s)' % (e.errno, e.strerror))
        log.error(msg)
        sys.stderr.write((msg + '\n'))
        sys.exit(1)
    log.debug('Fork    1    ok')
    os.chdir('/')
    os.setsid()
    if self.autorestart:
        logging.info('Running    with    auto-restart    ON')
        AgentSupervisor.start(parent_func=None, child_func=None)
    else:
        try:
            pid = os.fork()
            if (pid > 0):
                sys.exit(0)
        except OSError as e:
            msg = ('fork    #2    failed:    %d    (%s)' % (e.errno, e.strerror))
            logging.error(msg)
            sys.stderr.write((msg + '\n'))
            sys.exit(1)
    if (sys.platform != 'darwin'):
        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())
    log.info('Daemon    started')
