def daemonize(pid_file, cwd="/"):
    """Background the current process"""

    log.debug("daemonizing process")

    # BROKEN: the pid file may have already been created by write_pid
    # however, I'm not even using nagcat in daemon mode right now so
    # I'll just leave this commented out for now...
    # Also, this has a major race condition...
    #try:
    #    # A trivial check to see if we are already running
    #    pidfd = open(pid_file)
    #    pid = int(pidfd.readline().strip())
    #    pidfd.close()
    #    os.kill(pid, 0)
    #except (IOError, OSError):
    #    pass # Assume all is well if the test raised errors
    #else:
    #    log.error("PID file exits and process %s is running!" % pid)
    #    sys.exit(1)

    try:
        pidfd = open(pid_file, 'w')
    except __HOLE__, ex:
        log.error("Failed to open PID file %s" % pid_file)
        log.error("Error: %s" % (ex,))
        sys.exit(1)

    if os.fork() > 0:
        os._exit(0)

    os.chdir(cwd)
    os.setsid()

    if os.fork() > 0:
        os._exit(0)

    pidfd.write("%s\n" % os.getpid())
    pidfd.close()
dataset/ETHPy150Open marineam/nagcat/python/nagcat/util.py/daemonize