code: def daemonize_posix(self):
          
          logger.info('daemonize_posix')
          try:
              pid = os.fork()
              if pid > 0:
                  logger.debug('forked first child, pid = %d' % (pid,))
                  return pid
              logger.debug('in child after first fork, pid = %d' % (pid, ))
          except OSError as error:
              logger.exception('fork #1')
              sys.stderr.write("fork #1 failed: %d (%s)\n" % (error.errno, error.strerror))
              sys.exit(1)
  
          # decouple from parent environment
          os.chdir("/")
          os.setsid()
          os.umask(0)
  
          # do second fork
          try:
              pid = os.fork()
              if pid > 0:
                  # exit from second parent
                  logger.debug('forked second child, pid = %d, exiting' % (pid,))
                  sys.exit(0)
          except OSError as error:
              logger.exception('fork #2')
              sys.stderr.write("fork #2 failed: %d (%s)\n" % (error.errno, error.strerror))
              sys.exit(1)
  
          # redirect standard file descriptors
          logger.info('daemonized, pid = %d' % (pid, ))
          sys.stdin.flush()
          sys.stdout.flush()
          sys.stderr.flush()
  
          os.dup2(self.stdin.fileno(), sys.stdin.fileno())
          os.dup2(self.stdout.fileno(), sys.stdout.fileno())
          os.dup2(self.stderr.fileno(), sys.stderr.fileno())
  
          # write pidfile
          atexit.register(self.delpid)
          pid = str(os.getpid())
          with open(self.pidfile, 'w+') as fd:
              fd.write("%s\n" % pid)
docs: 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