Check if process exists then fail, otherwise clean up.
 @return [Boolean] `false` if no PID file exists, `true` if it cleaned up.
423233
def check_existing_pid
      return false unless pid_file_exists?
      pid = read_pid
      fail 'Existing process found.' if pid > 0 && pid_exists?(pid)
      delete_pid
    end
1365686
def check_subprocess(self):
        
        exit_code = self.process.poll()
        if exit_code is not None and exit_code != 0:
            # The main process exited with an error. Clean up the children
            # if any.
            self._kill_all_kids(self._sig_kill)
            self._clear_process()
            raise ProcessExitedWithError(self, exit_code)

        return self.after_start_check()
657698
def stop
    return self unless running?
    if @pid
      begin
        ::Process.kill 'TERM', @pid
        ::Process.wait @pid
      rescue SystemCallError
        # Process died on its own.
      ensure
        @pid = nil
      end
    end

    FileUtils.rm_rf @data_dir if File.exist?(@data_dir)
    @running = false
    self
  end
1229318
def status(self):
		
		# Get the pid from the pidfile
		try:
			pf = file(self.pidfile,'r')
			pid = int(pf.read().strip())
			pf.close()
		except IOError:
			pid = None

		if not pid:
			return False

		try:
			return os.path.exists("/proc/{0}".format(pid))
		except OSError:
			return False
91881
def is_running?
      return false if state != "exporting"
      begin
        Process.getpgid(exporter_pid)
        raise Exceptions::ExportIgnored.new("Ignored")
      rescue Errno::ESRCH
        return false
      end
    end
1114903
def process_exists(pid=None):
    
    if not pid:
        pid = current_pid()
    elif callable(pid):
        pid = pid()

    if pid and psutil.pid_exists(pid):
        pname = psutil.Process(pid).name()
        if os.name == 'nt':
            return os.path.splitext(pname)[0], pid
        return pname, pid
    return None, None
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))
912917
def _pid_is_alive(cls, pid, timeout):
        """"""
        try:
            proc = psutil.Process(pid)
        except psutil.NoSuchProcess:
            return False

        try:
            proc.wait(timeout=timeout)
        except psutil.TimeoutExpired:
            return True

        return False
122027
def pid_exists(value, pidtype=None):
    
    try:
        PersistentIdentifier.get(pidtype, value)
        return True
    except PIDDoesNotExistError:
        return False
1132528
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False):
    ''
    if isinstance(pids, (int, float, long)):
        pids = [pids]
    pids = str2list(pids, map_=unicode)
    procs = map(unicode, os.listdir('/proc'))
    running = [pid for pid in pids if pid in procs]
    logger.warn(
        "Found %s pids running: %s" % (len(running),
                                       running))
    prefix = prefix.rstrip('.') if prefix else None
    for pid in pids:
        if prefix:
            _prefix = prefix
        else:
            _prefix = unicode(pid)
        # remove non-running procs
        if pid in running:
            continue
        if multi:
            pid_file = '%s%s.pid' % (_prefix, pid)
        else:
            pid_file = '%s.pid' % (_prefix)
        path = os.path.join(pid_dir, pid_file)
        if os.path.exists(path):
            logger.debug("Removing pidfile: %s" % path)
            try:
                remove_file(path)
            except OSError as e:
                logger.warn(e)
    return running
787158
def _wait_for_process(self, pid, name):
        
        try:
            logging.debug("Waiting for process %s with pid %s", name, pid)
            unused_pid, exitcode, ru_child = os.wait4(pid, 0)
            return exitcode, ru_child
        except OSError as e:
            if self.PROCESS_KILLED and e.errno == errno.EINTR:
                # Interrupted system call seems always to happen
                # if we killed the process ourselves after Ctrl+C was pressed
                # We can try again to get exitcode and resource usage.
                logging.debug("OSError %s while waiting for termination of %s (%s): %s.",
                              e.errno, name, pid, e.strerror)
                try:
                    unused_pid, exitcode, ru_child = os.wait4(pid, 0)
                    return exitcode, ru_child
                except OSError:
                    pass # original error will be handled and this ignored

            logging.critical("OSError %s while waiting for termination of %s (%s): %s.",
                             e.errno, name, pid, e.strerror)
            return (0, None)
1141103
def execute &block
      raise 'Previous process still exists' unless pipes.empty?

      # clear callbacks
      @callbacks = []
      @errbacks = []

      pid, stdin, stdout, stderr = POSIX::Spawn.popen4 @command.to_s

      @pid = pid
      @stdin  = attach_pipe_handler :stdin, stdin
      @stdout = attach_pipe_handler :stdout, stdout
      @stderr = attach_pipe_handler :stderr, stderr

      if block
        block.call self
      elsif @execution_proc
        @execution_proc.call self
      end
      self
    end
206102
public function isProcessRunning($pid) {
        if (!$pid) {
            return false;
        }

        // Is the PID running?
        $running = posix_kill($pid, 0);
        if (!$running) {
            return false;
        }

        // Did we have trouble pinging that PID?
        $psExists = !(bool)posix_get_last_error();

        return $psExists;
    }
124720
def pid
      contents = File.read(self.pid_file).strip rescue ''
      real_pid = contents =~ /^\d+$/ ? contents.to_i : nil

      if real_pid
        @pid = real_pid
        real_pid
      else
        @pid
      end
    end
235789
def confirm_lock(lockfile):
    
    pidfile = open(lockfile, "r")
    pidfile_pid = pidfile.readline().strip()
    pidfile.close()
    if int(pidfile_pid) != os.getpid():
        raise RuntimeError, ("pidfile %s contains pid %s; expected pid %s!" %
                             (lockfile, os.getpid(), pidfile_pid))
    return True
329909
def _is_pid_running_on_windows(pid):
    
    import ctypes.wintypes

    kernel32 = ctypes.windll.kernel32
    handle = kernel32.OpenProcess(1, 0, pid)
    if handle == 0:
        return False
    exit_code = ctypes.wintypes.DWORD()
    ret = kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code))
    is_alive = (ret == 0 or exit_code.value == _STILL_ALIVE)  # pylint: disable=undefined-variable
    kernel32.CloseHandle(handle)
    return is_alive
205883
def check_process(pidfile):
    
    # Check pid file
    try:
        handle = open(pidfile, 'r')
    except IOError as exc:
        if exc.errno == errno.ENOENT:
            # pid file disappeared
            return False, 0
        raise

    try:
        pid = int(handle.read().strip(), 10)
    except (TypeError, ValueError) as exc:
        raise EnvironmentError("Invalid PID file '%s' (%s), won't start!" % (pidfile, exc))
    finally:
        handle.close()

    # Check process
    try:
        os.kill(pid, 0)
    except EnvironmentError as exc:
        return False, pid
    else:
        return True, pid