def daemonize(username=""):
    if os.fork() != 0:
        os._exit(0)
    os.setsid()
    if username:
        uid = pwd.getpwnam(username)[2]
        os.setuid(uid)
    if os.fork() != 0:
        os._exit(0)
    # create the pidfile
    pidfile = file(settings.PIDFILE, "w")
    pidfile.write("%d\n" % os.getpid())
    pidfile.close()
    # register a cleanup callback
    pidfile = os.path.abspath(settings.PIDFILE)

    def delpidfile():
        os.remove(pidfile)
    atexit.register(delpidfile)

    def delpidfileonSIGTERM(a, b):
        sys.exit()
    signal.signal(signal.SIGTERM, delpidfileonSIGTERM)
    #
    os.chdir("/")
    f = os.open(os.devnull, os.O_RDONLY)
    os.dup2(f, sys.stdin.fileno())
    os.close(f)
    f = os.open(os.devnull, os.O_WRONLY)
    os.dup2(f, sys.stdout.fileno())
    os.close(f)
    f = os.open(os.devnull, os.O_WRONLY)
    os.dup2(f, sys.stderr.fileno())
    os.close(f)
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcherd.py/daemonize/original