Check (in pid file) if there isn't already a daemon running.
        If yes and do_replace: kill it.
        Keep in self.fpid the File object to the pid file. Will be used by writepid.

        :return: None
542228
def check_parallel_run(self):  # pragma: no cover, not with unit tests...
        
        # TODO: other daemon run on nt
        if os.name == 'nt':  # pragma: no cover, not currently tested with Windows...
            logger.warning("The parallel daemon check is not available on Windows")
            self.__open_pidfile(write=True)
            return

        # First open the pid file in open mode
        self.__open_pidfile()
        try:
            pid_var = self.fpid.readline().strip(' \r\n')
            if pid_var:
                pid = int(pid_var)
                logger.info("Found an existing pid (%s): '%s'", self.pid_filename, pid_var)
            else:
                logger.debug("Not found an existing pid: %s", self.pid_filename)
                return
        except (IOError, ValueError) as err:
            logger.warning("PID file is empty or has an invalid content: %s", self.pid_filename)
            return

        if pid == os.getpid():
            self.pid = pid
            return

        try:
            logger.debug("Testing if the process is running: '%s'", pid)
            os.kill(pid, 0)
        except OSError:
            # consider any exception as a stale pid file.
            # this includes :
            #  * PermissionError when a process with same pid exists but is executed by another user
            #  * ProcessLookupError: [Errno 3] No such process
            self.pre_log.append(("DEBUG", "No former instance to replace"))
            logger.info("A stale pid file exists, reusing the same file")
            return

        if not self.do_replace:
            self.exit_on_error("A valid pid file still exists (pid=%s) and "
                               "I am not allowed to replace. Exiting!" % pid, exit_code=3)

        self.pre_log.append(("DEBUG", "Replacing former instance: %d" % pid))
        try:
            pgid = os.getpgid(pid)
            # SIGQUIT to terminate and dump core
            os.killpg(pgid, signal.SIGQUIT)
        except os.error as err:
            if err.errno != errno.ESRCH:
                raise

        self.fpid.close()
        # TODO: give some time to wait that previous instance finishes?
        time.sleep(1)
        # we must also reopen the pid file in write mode
        # because the previous instance should have deleted it!!
        self.__open_pidfile(write=True)
334759
def kill_process(process_name):
    
    try:
        sys.stdout.write('killing: {0} {{ \n'.format(process_name))
        pid = get_process_pid(process_name)
        if pid is not None and psutil.pid_exists(int(pid)):
            p = psutil.Process(pid)
            p.kill()
            p.wait()
            remove_pid_file(process_name)
    except Exception as e:
        sys.stderr.write('Exception on killing {0} : {1} \n'.format(process_name, e))
    finally:
        sys.stdout.write('}')
931819
private static void writePid(String file, boolean ignorePidFile) {
      File pidFile = new File(file);
      if(pidFile.exists()) {
        Long oldPid = getPid(pidFile);
        if(oldPid==null) {
          pidFile.delete();
        } else {
          log.warn("\n\t==================================\n\tThe OpenTSDB PID file [" + file + "] already exists for PID [" + oldPid + "]. \n\tOpenTSDB might already be running.\n\t==================================\n");
          if(!ignorePidFile) {
            log.warn("Exiting due to existing pid file. Start with option --ignore-existing-pid to overwrite"); 
            System.exit(-1);
          } else {
            log.warn("Deleting existing pid file [" + file + "]");
            pidFile.delete();
          }
        }
      }
      pidFile.deleteOnExit();
      File pidDir = pidFile.getParentFile();
      FileOutputStream fos = null;
      try {
        if(!pidDir.exists()) {
          if(!pidDir.mkdirs()) {
            throw new Exception("Failed to create PID directory [" + file + "]");
          }
        }     
        fos = new FileOutputStream(pidFile);      
        String PID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        fos.write(String.format("%s%s", PID, EOL).getBytes());
        fos.flush();
        fos.close();
        fos = null;
        log.info("PID [" + PID + "] written to pid file [" + file + "]");
      } catch (Exception ex) {
        log.error("Failed to write PID file to [" + file + "]", ex);
        throw new IllegalArgumentException("Failed to write PID file to [" + file + "]", ex);
      } finally {
        if(fos!=null) try { fos.close(); } catch (Exception ex) { /* No Op */ }
      }
    }
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
818110
public void startIfNotRunning() {
        boolean isStorageRunning = daemonExecutor.isProcessRunning(STORAGE_PIDFILE);
        if (isStorageRunning) {
            System.out.println(DISPLAY_NAME + " is already running");
        } else {
            FileUtils.deleteQuietly(STORAGE_PIDFILE.toFile()); // delete dangling STORAGE_PIDFILE, if any
            start();
        }
    }
1182618
def status(self):
        

        if self.pid is None:
            self.pid = self.read_pid()
        if self.pid is None:
            sp = BackgroundProcess.objects.filter(pk=1).first()
            if sp:
                self.pid = sp.pid
        if self.pid is None or self.pid == 0:
            self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
            return False
        if self.pid != getpid():
            # calling from outside the daemon instance
            try:
                kill(self.pid, signal.SIGUSR2)
                return True
            except OSError as e:
                if e.errno == errno.ESRCH:
                    return False
                else:
                    return False

        process_list = []
        for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
            process_list.append(process)
            process_list += list(process.backgroundprocess_set.filter())
        for process in process_list:
            logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pk))
            logger.debug('%s, process_id %d' % (self.label, self.process_id))
641658
def start(self, *args):
        

        if os.path.exists(self.pidfile):
            msg = "pidfile exists. Exit.\n"
            sys.stderr.write(msg % self.pidfile)
            sys.exit(1)

        self.daemonize()
        self.run(*args)
1031315
function pidFind(pid) {
  if (!_.isFinite(pid)) return false;
  try {
    if (runningAsRoot()) {
      return process.kill(pid, 0);
    } else {
      return !!ps(pid);
    }
  } catch (e) {
    return false;
  }
}
921717
void dropPidOrDie() {
        if (!dropPidFile()) {
            LOG.error("Pid file {} already exists... exiting.", pidFilename);

            // print to the console as well
            System.err.println("Pid file already exists... exiting.");
            System.err.flush();
            System.exit(-1);
        }
    }
1082527
def start_none
      unless options[:ontop]
        Daemonize.daemonize(output_logfile, @group.app_name)
      else
        Daemonize.simulate(output_logfile)
      end

      @pid.pid = Process.pid

      # We need this to remove the pid-file if the applications exits by itself.
      # Note that <tt>at_text</tt> will only be run if the applications exits by calling
      # <tt>exit</tt>, and not if it calls <tt>exit!</tt> (so please don't call <tt>exit!</tt>
      # in your application!
      #
      at_exit do
        begin; @pid.cleanup; rescue ::Exception; end

        # If the option <tt>:backtrace</tt> is used and the application did exit by itself
        # create a exception log.
        if options[:backtrace] && !options[:ontop] && !$daemons_sigterm
          begin; exception_log; rescue ::Exception; end
        end

      end

      # This part is needed to remove the pid-file if the application is killed by
      # daemons or manually by the user.
      # Note that the applications is not supposed to overwrite the signal handler for
      # 'TERM'.
      #
      trap(SIGNAL) do
        begin; @pid.cleanup; rescue ::Exception; end
        $daemons_sigterm = true

        if options[:hard_exit]
          exit!
        else
          exit
        end
      end
    end
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()
79131
def start(self):
        
        # If pidfile already exists, we should read pid from there; to overwrite it, if locking
        # will fail, because locking attempt somehow purges the file contents.
        if os.path.isfile(self.pid):
            with open(self.pid, "r") as old_pidfile:
                old_pid = old_pidfile.read()
        # Create a lockfile so that only one instance of this daemon is running at any time.
        try:
            lockfile = open(self.pid, "w")
        except IOError:
            print("Unable to create the pidfile.")
            sys.exit(1)
        try:
            # Try to get an exclusive lock on the file. This will fail if another process has the file
            # locked.
            fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError:
            print("Unable to lock on the pidfile.")
            # We need to overwrite the pidfile if we got here.
            with open(self.pid, "w") as pidfile:
                pidfile.write(old_pid)
            sys.exit(1)

        # skip fork if foreground is specified
        if not self.foreground:
            # Fork, creating a new process for the child.
            try:
                process_id = os.fork()
            except OSError as e:
                self.logger.error("Unable to fork, errno: {0}".format(e.errno))
                sys.exit(1)
            if process_id != 0:
                if self.keep_fds:
                    # This is the parent process. Exit without cleanup,
                    # see https://github.com/thesharp/daemonize/issues/46
                    os._exit(0)
                else:
                    sys.exit(0)
            # This is the child process. Continue.

            # Stop listening for signals that the parent process receives.
            # This is done by getting a new process id.
            # setpgrp() is an alternative to setsid().
            # setsid puts the process in a new parent group and detaches its controlling terminal.
            process_id = os.setsid()
            if process_id == -1:
                # Uh oh, there was a problem.
                sys.exit(1)

            # Add lockfile to self.keep_fds.
            self.keep_fds.append(lockfile.fileno())

            # Close all file descriptors, except the ones mentioned in self.keep_fds.
            devnull = "/dev/null"
            if hasattr(os, "devnull"):
                # Python has set os.devnull on this system, use it instead as it might be different
                # than /dev/null.
                devnull = os.devnull

            if self.auto_close_fds:
                for fd in range(3, resource.getrlimit(resource.RLIMIT_NOFILE)[0]):
                    if fd not in self.keep_fds:
                        try:
                            os.close(fd)
                        except OSError:
                            pass

            devnull_fd = os.open(devnull, os.O_RDWR)
            os.dup2(devnull_fd, 0)
            os.dup2(devnull_fd, 1)
            os.dup2(devnull_fd, 2)
            os.close(devnull_fd)

        if self.logger is None:
            # Initialize logging.
            self.logger = logging.getLogger(self.app)
            self.logger.setLevel(logging.DEBUG)
            # Display log messages only on defined handlers.
            self.logger.propagate = False

            # Initialize syslog.
            # It will correctly work on OS X, Linux and FreeBSD.
            if sys.platform == "darwin":
                syslog_address = "/var/run/syslog"
            else:
                syslog_address = "/dev/log"

            # We will continue with syslog initialization only if actually have such capabilities
            # on the machine we are running this.
            if os.path.exists(syslog_address):
                syslog = handlers.SysLogHandler(syslog_address)
                if self.verbose:
                    syslog.setLevel(logging.DEBUG)
                else:
                    syslog.setLevel(logging.INFO)
                # Try to mimic to normal syslog messages.
                formatter = logging.Formatter("%(asctime)s %(name)s: %(message)s",
                                              "%b %e %H:%M:%S")
                syslog.setFormatter(formatter)

                self.logger.addHandler(syslog)

        # Set umask to default to safe file permissions when running as a root daemon. 027 is an
        # octal number which we are typing as 0o27 for Python3 compatibility.
        os.umask(0o27)

        # Change to a known directory. If this isn't done, starting a daemon in a subdirectory that
        # needs to be deleted results in "directory busy" errors.
        os.chdir(self.chdir)

        # Execute privileged action
        privileged_action_result = self.privileged_action()
        if not privileged_action_result:
            privileged_action_result = []

        # Change owner of pid file, it's required because pid file will be removed at exit.
        uid, gid = -1, -1

        if self.group:
            try:
                gid = grp.getgrnam(self.group).gr_gid
            except KeyError:
                self.logger.error("Group {0} not found".format(self.group))
                sys.exit(1)

        if self.user:
            try:
                uid = pwd.getpwnam(self.user).pw_uid
            except KeyError:
                self.logger.error("User {0} not found.".format(self.user))
                sys.exit(1)

        if uid != -1 or gid != -1:
            os.chown(self.pid, uid, gid)

        # Change gid
        if self.group:
            try:
                os.setgid(gid)
            except OSError:
                self.logger.error("Unable to change gid.")
                sys.exit(1)

        # Change uid
        if self.user:
            try:
                uid = pwd.getpwnam(self.user).pw_uid
            except KeyError:
                self.logger.error("User {0} not found.".format(self.user))
                sys.exit(1)
            try:
                os.setuid(uid)
            except OSError:
                self.logger.error("Unable to change uid.")
                sys.exit(1)

        try:
            lockfile.write("%s" % (os.getpid()))
            lockfile.flush()
        except IOError:
            self.logger.error("Unable to write pid to the pidfile.")
            print("Unable to write pid to the pidfile.")
            sys.exit(1)

        # Set custom action on SIGTERM.
        signal.signal(signal.SIGTERM, self.sigterm)
        atexit.register(self.exit)

        self.logger.warning("Starting daemon.")

        try:
            self.action(*privileged_action_result)
        except Exception:
            for line in traceback.format_exc().split("\n"):
                self.logger.error(line)
1149110
def pid(self):
        
        # We can't possibly be running if our base_pathname isn't defined.
        if not self.base_pathname:
            return None
        try:
            pidfile = os.path.join(self.base_pathname, 'postmaster.pid')
            return int(open(pidfile).readline())
        except (IOError, OSError):
            return None
73758
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)
1126407
def write_pid(file)
      begin
        File.open(file, "w") do |pid_file|
          pid_file.puts(Process.pid)
        end
      rescue
        @logger.fatal("could not write to pid file", :pid_file => file)
        @logger.fatal("SENSU NOT RUNNING!")
        exit 2
      end
    end
89938
def pid(self):
        """"""
        try:

            os.remove(self.pidfile)

        except IOError:

            if not os.path.isfile(self.pidfile):

                return None

            LOG.exception("Failed to clear pidfile {0}).".format(self.pidfile))
            sys.exit(exit.PIDFILE_INACCESSIBLE)
669836
def stop(kill_arg=nil)
      if self.daemon_running?
        kill_pid(kill_arg || options[:kill])
        
        if until_true(MAX_START_TRIES) { self.daemon_stopped? }
          FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
          log "Daemonized process killed after term."
        else
          log "Failed to kill daemonized process"
          if options[:force]
            kill_pid(kill_arg || options[:kill], 'KILL')

            if until_true(MAX_START_TRIES) { self.daemon_stopped? }
              FileUtils.rm options[:pid_path] # Only kill if we stopped the daemon
              log "Daemonized process killed after kill."
            end
          end
        end
      else # not running
        log "No #{@name} processes are running"
        false
      end
    end