Turn the running process into a proper daemon according to PEP3143.

    Args:
    pidfile --The pidfile to create.
485160
def daemonize(pidfile=None):
    

    # Prevent core dumps
    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))

    # Change working directory
    os.chdir("/")

    # Change file creation mask
    os.umask(0)

    # Detach process context: do double fork
    pid = os.fork()
    if pid > 0:
        os._exit(0)
    os.setsid()
    pid = os.fork()
    if pid > 0:
        os._exit(0)

    # Create signal handler for SIGTERM
    def terminate(signal, stack_frame):
        msg = 'Terminating on signal {}'.format(signal)
        logger.info(msg)
        raise SystemExit(msg)
    signal.signal(signal.SIGTERM, terminate)

    # Redirect input/output streams
    streams = [sys.stdin, sys.stdout, sys.stderr]
    for stream in streams:
        devnull = os.open(os.devnull, os.O_RDWR)
        os.dup2(devnull, stream.fileno())

    # Close file descriptors
    for fd in [stream.fileno() for stream in streams]:
        try:
            os.close(fd)
        except OSError as err:
            if err.errno == errno.EBADF:
                # File descriptor was not open
                pass

    # Create pidfile
    if pidfile is None or pidfile.strip() == '':
        logger.debug('Empty pidfile set')
    else:
        pid = os.getpid()
        try:
            with open(pidfile, 'w') as f:
                f.write('{}\n'.format(pid))
                f.close()
        except EnvironmentError:
            logger.error('Failed to create pidfile at {}'.format(pidfile))

        def remove_pid_file():
            os.remove(pidfile)

        atexit.register(remove_pid_file)

    logger.debug('Process daemonized')
348833
def _get_pidfile_path(self):
        
        if self.config.daemon.pidfile:
            pidfile = path.abspath(self.config.daemon.pidfile)
            if not os.access(path.dirname(pidfile), os.W_OK):
                raise ValueError('Cannot write to specified pid file path'
                                 ' %s' % pidfile)
            return pidfile
        app = sys.argv[0].split('/')[-1]
        for pidfile in ['%s/pids/%s.pid' % (os.getcwd(), app),
                        '/var/run/%s.pid' % app,
                        '/var/run/%s/%s.pid' % (app, app),
                        '/var/tmp/%s.pid' % app,
                        '/tmp/%s.pid' % app,
                        '%s.pid' % app]:
            if os.access(path.dirname(pidfile), os.W_OK):
                return pidfile
        raise OSError('Could not find an appropriate place for a pid file')
97138
def running(self):
        

        # check if task is active and pid file exists
        return (not self._exited and os.path.isfile(self._pidfile)
                and self._task.active)
1102540
def run():
    
    settings.parse_args()
    pid_name = "gnotty-%s-%s.pid" % (settings.HTTP_HOST, settings.HTTP_PORT)
    pid_file = settings.PID_FILE or os.path.join(gettempdir(), pid_name)
    if settings.KILL:
        if kill(pid_file):
            print "Daemon killed"
        else:
            print "Could not kill any daemons"
        return
    elif kill(pid_file):
        print "Running daemon killed"
    if settings.DAEMON:
        daemonize(pid_file)
    serve_forever()
554498
public function setPidFile($pidFile)
    {
        $dir = realpath(dirname($pidFile));
        $filename = basename($pidFile);

        if (substr($pidFile, -1) == '/' or $filename == '.') {
            throw new \InvalidArgumentException('The pid file "'.$pidFile.'" must be a valid file path');
        }

        if (!is_dir($dir)) {
            throw new \RuntimeException('The pid file directory "'.$dir.'" does not exist');
        }

        if (!is_writeable($dir)) {
            throw new \RuntimeException('The pid file directory "'.$dir.'" is not writeable');
        }

        $this->pidFile = $dir.'/'.$filename;

        if (file_exists($this->pidFile) and posix_kill((int)trim(file_get_contents($this->pidFile)), 0)) {
            throw new \RuntimeException('Pid file "'.$pidFile.'" already exists and worker is still running.');
        }

        if (!file_put_contents($this->pidFile, getmypid(), LOCK_EX)) {
            throw new \RuntimeException('Could not write pid to file "'.$pidFile.'"');
        }
    }
799082
def load_pid(pidfile):
    
    if pidfile and os.path.isfile(pidfile):
        with open(pidfile, "r", encoding="utf-8") as fobj:
            return int(fobj.readline().strip())
    return 0
1073487
public function daemonize() {

        // fork script
        $pid = $this->fork();

        // detach from current terminal (if any)
        $this->detach();

        // update pid reference (we have a new daemon)
        $this->pid = $pid;

        // start process daemon
        $this->start();

    }
32073
def write_pidfile(pidfile):
    
    pid = os.getpid()
    if pidfile:
        with open(pidfile, "w", encoding="utf-8") as fobj:
            fobj.write(six.u(str(pid)))
    return pid
551954
def daemon_stop(pidfile, sig=None):
    
    logger.debug("stop daemon application pidfile={pidfile}.".format(pidfile=pidfile))
    pid = load_pid(pidfile)
    logger.debug("load pid={pid}".format(pid=pid))
    if not pid:
        six.print_("Application is not running or crashed...", file=os.sys.stderr)
        os.sys.exit(195)
    process_kill(pid, sig)
    return pid
15122
def become_daemon(*args, **kwargs):
    
    if django.VERSION >= (1, 9):
        from .daemonize import become_daemon
    else:
        from django.utils.daemonize import become_daemon
    return become_daemon(*args, **kwargs)
416627
def create_process(daemon, name, callback, *callbackParams):
    
    bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams)
    return bp
515063
def start(self):
        """"""
        if self._already_running():
            message = 'pid file %s already exists. Daemon already running?\n'
            sys.stderr.write(message % self.pid_file)
            return 0
        self.set_gid()
        self.set_uid()
        # Create log files (if configured) with the new user/group. Creating
        # them as root would allow symlink exploits.
        self.setup_logging()
        # Create pid file with new user/group. This ensures we will be able
        # to delete the file when shutting down.
        self.daemonize()
        try:
            self.run()
        except Exception:
            self.logger.exception('Exception while running the daemon:')
            return 1
        return 0
134114
def pid_from_file
      if File.exist?(pid_file_path)
        pid = File.read(pid_file_path)
        pid.length > 0 ? pid.strip.to_i : nil
      else
        nil
      end
    end
1155569
def _write_pidfile(self):
        """"""
        LOGGER.debug('Writing pidfile: %s', self.pidfile_path)
        with open(self.pidfile_path, "w") as handle:
            handle.write(str(os.getpid()))
845792
def daemonize(logfile):
    
    
    # turn off GC across the fork
    gc.collect(2)
    gc.collect(1)
    gc.collect(0)
    gc.disable()
    
    child_pid = os.fork()

    if child_pid == 0:
        # child!
        sys.stdin.close()
        os.dup2(logfile.fileno(), sys.stdout.fileno())
        os.dup2(logfile.fileno(), sys.stderr.fileno())

        soft_num_open_files, hard_num_open_files = resource.getrlimit(resource.RLIMIT_NOFILE)
        if hard_num_open_files == resource.RLIM_INFINITY:
            # guess
            hard_num_open_files = 1024

        # we don't have many other fds open yet
        for i in range(3, hard_num_open_files):
            if i == logfile.fileno():
                continue

            try:
                os.close(i)
            except:
                pass

        os.setsid()

        daemon_pid = os.fork()
        if daemon_pid == 0:
            # daemon! chdir and return
            os.chdir('/')
            gc.enable()
            gc.collect(2)
            gc.collect(1)
            gc.collect(0)
            return 0

        elif daemon_pid > 0:
            # parent (intermediate child)
            sys.exit(0)

        else:
            # error
            sys.exit(1)

    elif child_pid > 0:
        # grand-parent (caller)
        # re-activate gc
        gc.enable()
        gc.collect(2)
        gc.collect(1)
        gc.collect(0)

        # wait for intermediate child.
        # panic if we don't hear back after 5 minutes
        timeout = 600
        if BLOCKSTACK_TEST:
            # wait around so we can attach gdb or whatever
            timeout = 60000

        for i in range(0, timeout):
            pid, status = os.waitpid(child_pid, os.WNOHANG)
            if pid == 0:
                # still waiting
                time.sleep(1)
                log.debug("Still waiting on {}".format(child_pid))
                continue

            # child has exited!
            if os.WEXITSTATUS(status) == 0:
                return child_pid
            else:
                log.error("Child exit status {}".format(status))
                return -1

        # child has not exited yet.  This is not okay.
        log.error("Child PID={} did not exit.  Killing it instead and failing...".format(child_pid))
        os.kill(child_pid, signal.SIGKILL)
        return -1
    
    else:
        # failed to fork 
        log.error("Failed to fork")
        return -1

    # parent! success
    return child_pid
946074
function killRunningProcess(procName, callback) {
  var pidFilePath = pidDir + procName + '.pid';
  fs.readFile(pidFilePath, function(err, pidData) {
    if (err) {
      return callback(err);
    } else {
      return exec('kill ' + pidData.toString(), function(err, stdout, stderr) {
	return callback(null);
      });
    }
  });
}
98130
def write_pid(pidfile):
    
    pid = str(os.getpid())
    try:
        with open(pidfile, mode='w') as _file:
            print("writing processID {p} to pidfile".format(p=pid))
            _file.write(pid)
    except OSError as exc:
        sys.exit("failed to write pidfile:{e}".format(e=exc))