kill WSGI processes that may be running in development
161808
def kill_process(procname, scriptname):
    """"""

    # from http://stackoverflow.com/a/2940878
    import signal
    import subprocess

    p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE)
    out, err = p.communicate()

    for line in out.decode().splitlines():
        if procname in line and scriptname in line:
            pid = int(line.split()[1])
            info('Stopping %s %s %d' % (procname, scriptname, pid))
            os.kill(pid, signal.SIGKILL)
586923
def __kill_if_not_shut_properly(self):
        
        import tempfile
        d = tempfile.gettempdir()
        name = os.path.join(d, "hoverpy.%i.%i"%(self._proxyPort, self._adminPort))
        if os.path.exists(name):
            logging.debug("pid file exists.. killing it")
            f = open(name, "r")
            pid = int(f.read())
            try:
                import signal
                os.kill(pid, signal.SIGTERM)
                logging.debug("killing %i"%pid)
            except:
                logging.debug("nothing to clean up")
                pass
            finally:
                os.unlink(name)
910262
def disown(cmd):
    """"""
    subprocess.Popen(cmd,
                     stdout=subprocess.DEVNULL,
                     stderr=subprocess.DEVNULL)
1221204
def clean_process_tree(*signal_handler_args):
    """"""
    parent = psutil.Process()
    procs = parent.children(recursive=True)
    if procs:
        print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...")

    for p in procs:
        with suppress(psutil.NoSuchProcess):
            p.terminate()
    _, alive = psutil.wait_procs(procs, timeout=0.5)  # 0.5 seems to work
    for p in alive:
        with suppress(psutil.NoSuchProcess):
            p.kill()

    try:
        signum = signal_handler_args[0]
    except IndexError:
        pass
    else:
        os._exit(signum)
1224025
def kill_process_children(pid):
    
    if sys.platform == "darwin":
        kill_process_children_osx(pid)
    elif sys.platform == "linux":
        kill_process_children_unix(pid)
    else:
        pass
620904
def kill_all(self):
        ''''''
        while self._num_workers > 0 and self._worker_backend_socket.poll(1000):
            msg = self._worker_backend_socket.recv_pyobj()
            self._worker_backend_socket.send_pyobj(None)
            self._num_workers -= 1
            self.report(f'Kill {msg[1:]}')
        # join all processes
        [worker.join() for worker in self._workers]
1301082
void stop() {
    if (!shouldRun(conf)) {
      return;
    }
    nodeHealthScriptScheduler.cancel();
    if (shexec != null) {
      Process p = shexec.getProcess();
      if (p != null) {
        p.destroy();
      }
    }
  }
1048006
def stop(self):
		
		if WAppsGlobals.log is not None and WLogApp.__log_handler__ is not None:
			WAppsGlobals.log.removeHandler(WLogApp.__log_handler__)

		WLogApp.__log_handler__ = None
		WAppsGlobals.log = None
754769
def kill(self):
        
        try:
            os.unlink(self.server_address)
        except OSError:
            if os.path.exists(self.server_address):
                raise
955060
def kill_all_process(self):
    
    if (runtime.get_active_config("cleanup_pending_process",False)):
      for process in self.get_processes():
        self.terminate(process.unique_id)
1043344
def killall(self):
        
        for pid in set(self):
            try:
                os.kill(pid, signal.SIGTERM)
            except OSError, e: # pragma: nocover
                if e.errno == errno.ESRCH:
                    "Process previously died on its own"
            self.remove(pid)
337255
protected function stop()
    {
        $pid = $this->getMasterPid();

        if (!$this->isRunning($pid)) {
            $this->output->writeln('<error>no swoole http server process running.</error>');
            return;
        }

        $this->output->writeln('Stopping swoole http server...');

        $isRunning = $this->killProcess($pid, SIGTERM, 15);

        if ($isRunning) {
            $this->output->error('Unable to stop the swoole_http_server process.');
            return;
        }

        $this->removePid();

        $this->output->writeln('> success');
    }
356554
def kill(self, dwExitCode = 0):
        
        hProcess = self.get_handle(win32.PROCESS_TERMINATE)
        win32.TerminateProcess(hProcess, dwExitCode)
571384
private void terminateWindowsProcess(InstanceConfiguration config)
    {
        log.info("Cleaning up at application shutdown...");

        String pid;
        try
        {
            pid = ProcessUtil.getElasticsearchPid(config.getBaseDir());
            log.debug("Read PID '" + pid + "' from pid file");
        }
        catch (Exception ex)
        {
            log.debug("Cannot read the PID from file; assuming the process is not running", ex);
            return;
        }
        
        boolean isAlive;
        try
        {
            isAlive = ProcessUtil.isWindowsProcessAlive(config, pid);
            log.debug("Process is still running: " + isAlive);
        }
        catch (Exception ex)
        {
            log.debug("Cannot determine if the process is running; assuming it is", ex);
            isAlive = true;
        }
        
        if (isAlive == false)
        {
            return;
        }
        
        log.info(String.format(
                "The Elasticsearch process [%d] is still running; stopping it...",
                config.getId()));
        
        CommandLine command = ProcessUtil.buildKillCommandLine(pid);
        for (int retry = 0; retry < 3; ++retry)
        {
            try
            {
                ProcessUtil.executeScript(config, command, true);
    
                log.info(String.format(
                        "... the Elasticsearch process [%d] has stopped.",
                        config.getId()));
                ProcessUtil.cleanupPid(config.getBaseDir());
            }
            catch (Exception e)
            {
                if (e.getMessage().contains("no running instance"))
                {
                    log.info(String.format(
                            "... the Elasticsearch process [%d] has stopped.",
                            config.getId()));
                    ProcessUtil.cleanupPid(config.getBaseDir());
                }
                else
                {
                    // sometimes taskkill fails with "The operation attempted is not supported."
                    // https://blogs.technet.microsoft.com/markrussinovich/2005/08/17/unkillable-processes/
                    // in that case, retry
                    if (retry < 2) {
                        try {
                            Thread.sleep(500);
                            continue;
                        } catch (InterruptedException e1) {
                            /* ignore */
                        }
                    }
                    log.error(String.format(
                            "Error while destroying the Elasticsearch process [%d]",
                            config.getId()),
                            e);
                }
            }
            break;
        }
    }
448840
def close(self):
        """"""
        if self._subprocess is not None:
            os.killpg(self._subprocess.pid, signal.SIGTERM)
            self._subprocess = None
144457
def kill_process_on_host(
    hostname,
    pattern
):
    

    status, stdout = run_command_on_agent(hostname, "ps aux | grep -v grep | grep '{}'".format(pattern))
    pids = [p.strip().split()[1] for p in stdout.splitlines()]

    for pid in pids:
        status, stdout = run_command_on_agent(hostname, "sudo kill -9 {}".format(pid))
        if status:
            print("Killed pid: {}".format(pid))
        else:
            print("Unable to killed pid: {}".format(pid))
1110505
def stop(pid):
    
    if psutil.pid_exists(pid):
      try:
        p = psutil.Process(pid)
        p.kill()
      except Exception:
        pass