Terminates process with PID `pid` and returns True if process finished
    during `timeout`. Current user must have permission to access process
    information.
776199
def terminate(pid, sig, timeout):
    ''''''
    os.kill(pid, sig)
    start = time.time()
    while True:
        try:
            # This is requireed if it's our child to avoid zombie. Also
            # is_running() returns True for zombie process.
            _, status = os.waitpid(pid, os.WNOHANG)
        except OSError as exc:
            if exc.errno != errno.ECHILD: # pragma: nocover
                raise
        else:
            if status:
                return True
        if not is_running(pid):
            return True
        if time.time()-start>=timeout:
            return False
        time.sleep(0.1)
1261254
def isprocess(pid, error=False):
    
    try:
        # Don't worry folks, no processes are harmed in the making of
        # this system call:
        os.kill(pid, 0)
        return True
    except OSError:
        return False
1124754
def _CheckStatusAnalysisProcess(self, pid):
    
    # TODO: Refactor this method, simplify and separate concerns (monitoring
    # vs management).
    self._RaiseIfNotRegistered(pid)

    if pid in self._completed_analysis_processes:
      status_indicator = definitions.STATUS_INDICATOR_COMPLETED
      process_status = {
          'processing_status': status_indicator}
      used_memory = 0

    else:
      process = self._processes_per_pid[pid]

      process_status = self._QueryProcessStatus(process)
      if process_status is None:
        process_is_alive = False
      else:
        process_is_alive = True

      process_information = self._process_information_per_pid[pid]
      used_memory = process_information.GetUsedMemory() or 0

      if self._worker_memory_limit and used_memory > self._worker_memory_limit:
        logger.warning((
            'Process: {0:s} (PID: {1:d}) killed because it exceeded the '
            'memory limit: {2:d}.').format(
                process.name, pid, self._worker_memory_limit))
        self._KillProcess(pid)

      if isinstance(process_status, dict):
        self._rpc_errors_per_pid[pid] = 0
        status_indicator = process_status.get('processing_status', None)

        if status_indicator == definitions.STATUS_INDICATOR_COMPLETED:
          self._completed_analysis_processes.add(pid)

      else:
        rpc_errors = self._rpc_errors_per_pid.get(pid, 0) + 1
        self._rpc_errors_per_pid[pid] = rpc_errors

        if rpc_errors > self._MAXIMUM_RPC_ERRORS:
          process_is_alive = False

        if process_is_alive:
          rpc_port = process.rpc_port.value
          logger.warning((
              'Unable to retrieve process: {0:s} (PID: {1:d}) status via '
              'RPC socket: http://localhost:{2:d}').format(
                  process.name, pid, rpc_port))

          processing_status_string = 'RPC error'
          status_indicator = definitions.STATUS_INDICATOR_RUNNING
        else:
          processing_status_string = 'killed'
          status_indicator = definitions.STATUS_INDICATOR_KILLED

        process_status = {
            'processing_status': processing_status_string}

    self._UpdateProcessingStatus(pid, process_status, used_memory)

    if status_indicator in definitions.ERROR_STATUS_INDICATORS:
      logger.error((
          'Process {0:s} (PID: {1:d}) is not functioning correctly. '
          'Status code: {2!s}.').format(
              process.name, pid, status_indicator))

      self._TerminateProcessByPid(pid)
466650
def kill_process(sig = 'TERM')
      content = IO.read(@options[:pid_file])
      pid = content.to_i
      fail("Invalid pid file content #{content.inspect}") if pid == 0
      begin
        Process.kill(sig, pid)
      rescue Errno::ESRCH => e
        fail("Could not find process with pid #{pid}")
      rescue Errno::EPERM => e
        fail("You don't have permissions to stop process #{pid}")
      rescue Exception => e
        fail(e.message)
      end
      true
    end
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))
158538
def stop(self, timeout=15):
        
        pp = self.pid
        if pp:
            try:
                kill_process_nicely(pp, timeout=timeout)
            except psutil.NoSuchProcess:
                pass
8444
def stop(self):
        
        if self.pid is None:

            return None

        try:

            while True:

                self.send(signal.SIGTERM)
                time.sleep(0.1)

        except RuntimeError as err:

            if "No such process" in str(err):

                LOG.info("Succesfully stopped the process.")
                return None

            LOG.exception("Failed to stop the process:")
            sys.exit(exit.STOP_FAILED)

        except TypeError as err:

            if "an integer is required" in str(err):

                LOG.info("Succesfully stopped the process.")
                return None

            LOG.exception("Failed to stop the process:")
            sys.exit(exit.STOP_FAILED)
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
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
408868
def kill_pid(self, pid):
        
        try:

            p = psutil.Process(pid)

            p.terminate()

            self.info_log('Killed [pid:%s][name:%s]' % (p.pid, p.name()))
        except psutil.NoSuchProcess:
            self.error_log('No such process: [pid:%s]' % pid)
46985
def save_exit_status(pid)
        logger.debug "Spawning thread to monitor process ID #{pid}"
        @success = nil
        Thread.start do
          logger.debug "Thread started, waiting for PID #{pid}"
          status = Process.waitpid2(pid).last.exitstatus
          logger.debug "Process exited with status #{status}"
          @success = (status == 0)
        end
      end
658984
def stop_subprocess(pid):
    """"""
    if hasattr(os, "kill"):
        import signal
        os.kill(pid, signal.SIGTERM)
    else:
        import win32api
        pid = win32api.OpenProcess(1, 0, pid)
        win32api.TerminateProcess(pid, 0)
    os.waitpid(pid, 0)
258358
def kill signal = 'TERM', wait = false
      Process.kill signal, self.pid
      val = status if wait
      @stdin.close
      @stdout.close
      @stderr.close
      val
    end
940214
def restart_process(self, pid):
        '''
        
        '''
        if self._restart_processes is False:
            return
        log.info(
            'Process %s (%s) died with exit status %s, restarting...',
            self._process_map[pid]['tgt'],
            pid,
            self._process_map[pid]['Process'].exitcode
        )
        # don't block, the process is already dead
        self._process_map[pid]['Process'].join(1)

        self.add_process(self._process_map[pid]['tgt'],
                         self._process_map[pid]['args'],
                         self._process_map[pid]['kwargs'])

        del self._process_map[pid]
175614
def kill(self):
        
        try:
            kill(int(self.get()), 9)
            
        # Failed to kill the process
        except Exception as e:
            self.die('Failed to kill process: {}'.format(str(e)))
            
        # Remove the stale PID file
        self.remove()
227109
function check() {
    if (terminated) {
      // Successfully terminated
      clearTimeout(t);
      return callback();
    }
    if ((Date.now() - start) < timeout) {
      // Still not terminated, try again
      signalTerm(childProcess, (err) => {
        if (err) { return callback(err); }
        t = setTimeout(check, retryDelay);
      });
    } else {
      // Still not terminated and the timeout has passed, either
      // kill the process (force) or provide an error
      clearTimeout(t);
      if (force) {
        signalKill(childProcess, callback);
      } else {
        callback(
          new Error(`Unable to gracefully terminate process ${childProcess.pid}`)
        );
      }
    }
  }
1216804
def _kill_process(proc):
    
    try:
        proc.kill()
    except AccessDenied:
        logs.debug(u'Rerun: process PID {} ({}) could not be terminated'.format(
            proc.pid, proc.exe()))