'Fork off as a daemon'

def daemonize(self):

    try:
        pid = os.fork()
        if (pid != 0):
            os._exit(0)
    except OSError as error:
        sys.stderr.write(u'fork    #1    failed:    {error_num}:    {error_message}\n'.format(error_num=error.errno, error_message=error.strerror))
        sys.exit(1)
    os.setsid()
    os.umask(0)
    try:
        pid = os.fork()
        if (pid != 0):
            os._exit(0)
    except OSError as error:
        sys.stderr.write(u'fork    #2    failed:    Error    {error_num}:    {error_message}\n'.format(error_num=error.errno, error_message=error.strerror))
        sys.exit(1)
    if self.create_pid:
        pid = os.getpid()
        logger.log(u'Writing    PID:    {pid}    to    {filename}'.format(pid=pid, filename=self.pid_file))
        try:
            with io.open(self.pid_file, u'w') as f_pid:
                f_pid.write(u'{0}\n'.format(pid))
        except EnvironmentError as error:
            logger.log_error_and_exit(u'Unable    to    write    PID    file:    {filename}    Error    {error_num}:    {error_message}'.format(filename=self.pid_file, error_num=error.errno, error_message=error.strerror))
    sys.stdout.flush()
    sys.stderr.flush()
    devnull = getattr(os, u'devnull', u'/dev/null')
    stdin = open(devnull)
    stdout = open(devnull, u'a+')
    stderr = open(devnull, u'a+')
    os.dup2(stdin.fileno(), getattr(sys.stdin, u'device', sys.stdin).fileno())
    os.dup2(stdout.fileno(), getattr(sys.stdout, u'device', sys.stdout).fileno())
    os.dup2(stderr.fileno(), getattr(sys.stderr, u'device', sys.stderr).fileno())
