def kill_proc_tree(pid, including_parent=True, timeout=5): try: parent = Process(pid) except NoSuchProcess: return children = parent.children(recursive=True) for child in children: if verbose.kill: print("killing {}".format(child.pid)) try: child.kill() child.terminate() except NoSuchProcess: pass gone, still_alive = wait_procs(children, timeout=timeout) if including_parent: try: if verbose.kill: print("killing {}".format(parent.pid)) parent.kill() parent.terminate() try: parent.wait(timeout) except TimeoutExpired: print("timeout expired, process may still be around: {}".format(parent.pid)) except NoSuchProcess: pass
def _kill(process: psutil.Process, timeout=5) -> bool: """Attempts to kill the process in a fail-safe manner and returns status Tries to terminate the process first and waits for it for the given timeout. If termination fails - attempts to kill the process instead and wait for it to die. Args: process(Process): the process that is to be killed timeout(int): the timeout to wait after each terminate/kill attempt Returns: obj(bool): True if the process has been killed/terminated, False if the process is still running after this method returns """ if not process.is_running(): return True try: process.terminate() try: process.wait(timeout) return True except: process.kill() try: process.wait(timeout) return True except: pass except: pass return not process.is_running()
def kill_process_group(self, pid): from psutil import Process parent = Process(pid) for child in parent.children(recursive=True): child.kill() parent.kill() parent.wait()
def kill_process_and_subs(): proc = Process(getpid()) subprocs = proc.children() for subproc in subprocs: subproc.terminate() stillalive = wait_procs(subprocs, timeout=2)[1] for p in stillalive: p.kill() proc.kill()
def terminate(self): self.alive = False try: parent = Process(self.process.pid) for child in parent.children(recursive=True): child.kill() parent.kill() except NoSuchProcess: pass
def kill_recursively(p: Process): """Kill a process and all its children.""" children = p.children() if children: for child in children: kill_recursively(child) try: p.kill() except NoSuchProcess: pass
def on_message(self, message, data): #print(message) module = message['payload']['module'] func = message['payload']['func'] PID = message['payload']['PID'] callback = self.funcMap[module][func][1] if callback(message['payload']['args'], data): p = Process(PID) p.kill() self.script.post({'type': 'wake', 'payload': None})
def close(self): try: process = Process(self.chrome.pid) for proc in process.children(recursive=True): proc.kill() process.kill() self.url = None print("chromium closed") except Exception as e: print("could not close chromium with exception: " + str(e))
def _psutil_kill_pid(pid): """ http://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows """ try: parent = Process(pid) for child in parent.children(recursive=True): child.kill() parent.kill() except NoSuchProcess: return
def kill(proc: Process): if proc.pid != this_pid: try: proc.kill() return True except NoSuchProcess: return True except AccessDenied: return False else: return False
def sig_int(signal_num, frame): LOG.error('signal: %s frame: %s', signal_num, frame) parent = Process(parent_id) for child in parent.children(): if child.pid != os.getpid(): LOG.error("exiting child: %s" % child.pid) child.kill() LOG.error("exiting parent: %s" % parent_id) parent.kill() LOG.error("exiting all: %s" % os.getpid()) Process(os.getpid()).kill()
def kill(self, pid=None): if self.running: pid = self._pid if pid is None else pid if pid_exists(pid): log.debug("killing process with pid %s" % pid) process = Process(pid) self._out_stream.stop() self._error_stream.stop() for proc in process.children(recursive=True): proc.kill() process.kill()
def safe_stop(proc: psutil.Process, kill: bool = False) -> None: """Do not crash on already stopped process. :param proc: target process :type proc: psutil.Process :param kill: use SIGKILL instead of SIGTERM :type kill: bool """ with contextlib.suppress(psutil.NoSuchProcess): if kill: proc.kill() proc.terminate()
def _stop(self): logging.info("Stopping service process %s", self.command) try: self._callFromThread(self._terminateProcess) except: if self.protocol.transport.pid: # In case something goes wrong let's try our best to not leave # running processes around. logging.info( "Service process didn't terminate, trying to kill it") process = Process(self.protocol.transport.pid) process.kill() process.wait(timeout=1)
def terminate(self): OutputHandler.print('Terminate called') with self.lock: OutputHandler.print('Terminate - LOCK ACQUIRED') if not self.terminated: OutputHandler.print('Terminate - BEFORE WAIT STDERR') self.wait_output() OutputHandler.print('Terminate - AFTER WAIT STDERR') self._alive = False OutputHandler.print('Terminate - SELF ALIVE == FALSE') is_exit_replaced = ExitHandler.is_replaced() if is_exit_replaced: ExitHandler.revert_exit() OutputHandler.print('Terminate - EXIT REVERTED') try: parent = Process(self.process.pid) OutputHandler.print(f'Terminate - parent == {parent}') for child in parent.children(recursive=True): OutputHandler.print(f'Terminate - child kill {child}') child.kill() OutputHandler.print(f'Terminate - parent kill {parent}') parent.kill() except NoSuchProcess: OutputHandler.print(f'Terminate - NO SUCH PROCESS') pass finally: OutputHandler.print(f'Terminate - finally before kill') self.process.kill() OutputHandler.print(f'Terminate - finally before wait') self.process.wait() self.process.stdout.close() self.process.stderr.close() self.process.stdin.close() if is_exit_replaced: ExitHandler.replace_exit() OutputHandler.print(f'Terminate - EXIT REPLACED AGAIN') self.terminated = True OutputHandler.print(f'Terminate - TERMINATED') OutputHandler.print(f'Terminate - finished')
def KillProcess(callback: dict, bot): pid = int(callback.data[2:]) chatid = callback.from_user.id Log(f"TaskManager >> Kill process {pid}", chatid) process = None try: process = Process(pid) if process != None: print(process) name = process.name() process.kill() except Exception as error: bot.send_message(chatid, Messages.taskmanager_process_kill_failed % (pid, error)) else: bot.send_message(chatid, Messages.taskmanager_process_kill_success % (name, pid))
def kill_process(process: psutil.Process = None, pid: int = None, expected_cmdline: list = None): process = process if process is not None else get_process_instance(pid) if process is None: return for child in process.children(recursive=True): try: if check_process(pid=child.pid): child.kill() except Exception as e: stat_logger.warning(f"kill {child.pid} process failed", exc_info=True) if check_process(pid=process.pid, expected_cmdline=expected_cmdline): process.kill()
def terminate(self): self.alive = False is_exit_replaced = ExitHandler.is_replaced() if is_exit_replaced: ExitHandler.revert_exit() try: parent = Process(self.process.pid) for child in parent.children(recursive=True): child.kill() parent.kill() except NoSuchProcess: pass finally: if is_exit_replaced: ExitHandler.replace_exit()
async def _close_process(self, proc: psutil.Process): try: proc.terminate() await asyncio.sleep(1) try: if proc.status() != psutil.STATUS_ZOMBIE: proc.kill() except Exception: pass except Exception: pass try: proc.wait(timeout=0) except Exception: pass
def wait_output(settings, popen): """Returns `True` if we can get output of the command in the `wait_command` time. Command will be killed if it wasn't finished in the time. """ proc = Process(popen.pid) try: proc.wait(settings.wait_command) return True except TimeoutExpired: for child in proc.get_children(recursive=True): child.kill() proc.kill() return False
def get_as_item(p: Process, *extra_actions): """Return an item - ready to be appended to the items list and be rendered by Albert. if Process is not a valid object (.name or .cmdline raise an exception) then return None """ name_field = cmdline(p) if not name_field: return None try: actions = [ v0.FuncAction("Terminate", lambda: p.terminate()), v0.FuncAction("Kill", lambda: p.kill()), v0.ClipAction("Get PID", f"{p.pid}"), v0.FuncAction( "Terminate matching names", lambda name=p.name(): kill_by_name(name, signal=signal.SIGTERM ), ), v0.FuncAction("Kill matching names", lambda name=p.name(): kill_by_name(name)), ] actions = [*extra_actions, *actions] return v0.Item( id=__title__, icon=icon_path, text=name_field, subtext="", completion=p.name(), actions=actions, ) except psutil.NoSuchProcess: return None
def restart(update, context): restart_message = sendMessage("Restarting...", context.bot, update) if Interval: Interval[0].cancel() alive.kill() procs = Process(web.pid) for proc in procs.children(recursive=True): proc.kill() procs.kill() clean_all() srun(["python3", "update.py"]) # Save restart message object in order to reply to it after restarting nox.kill() with open(".restartmsg", "w") as f: f.truncate(0) f.write(f"{restart_message.chat.id}\n{restart_message.message_id}\n") osexecl(executable, executable, "-m", "bot")
def kill_process_and_children(parent_process: psutil.Process, logger, timeout: int = 20) -> None: """Attempts to recursively kill the entire process tree under a given parent process""" try: for child in parent_process.children(): kill_process_and_children(child, logger) parent_process.kill() parent_process.wait(timeout=timeout) except psutil.NoSuchProcess: logger.debug("Process %i has already exited", parent_process.pid) pass except psutil.TimeoutExpired: logger.debug("Timeout while waiting for process %i to terminate" % parent_process.pid) pass
def a_proc_kill(proc: psutil.Process): """Kill a process asynchronously Args: proc: The process Returns: The result from proc.kill() """ return proc.kill()
def cancel_download(path): if os.path.exists(DOWNLOAD_HISTORY): with open(DOWNLOAD_HISTORY, 'rb') as fp: download_history = pickle.load(fp) else: print('Problem managing processes...') if path in download_history.keys(): pid = download_history[path].pid try: p = ProcessManager(pid) if p.is_running(): p.kill() except NoSuchProcess as e: print(e) if os.path.exists( os.path.join(DOWNLOAD_LOCATION, '{}incomplete'.format(path))): os.remove(os.path.join(DOWNLOAD_LOCATION, '{}incomplete'.format(path))) if os.path.exists(os.path.join(DOWNLOAD_LOCATION, path)): os.remove(os.path.join(DOWNLOAD_LOCATION, path)) return jsonify({'status': 'success'})
def _wait_output(popen, is_slow): """Returns `True` if we can get output of the command in the `settings.wait_command` time. Command will be killed if it wasn't finished in the time. :type popen: Popen :rtype: bool """ proc = Process(popen.pid) try: proc.wait(settings.wait_slow_command if is_slow else settings.wait_command) return True except TimeoutExpired: for child in proc.children(recursive=True): child.kill() proc.kill() return False
def stop(**kwargs): lock = PIDLockFile(os.path.join(RAMMON_PATH, "rammon.pid")) if try_systemd_stop(): logger.info("Stopping rammon daemon with systemd...") if lock.is_locked(): try: proc = Process(lock.read_pid()) proc.terminate() try: proc.wait(1) except TimeoutExpired: print("Rammon did not stop gracefully, killing it...") proc.kill() lock.break_lock() logger.info("Rammon stopped successfully") except NoSuchProcess: logger.warning( "Rammon was already stopped, but had not stopped cleanly.\n" "Breaking pidfile lock...") lock.break_lock() else: logger.error("Rammon is already stopped") sys.exit(1)
def kill_process(max_retry, p_instance: psutil.Process, p_name, kill_process_retry_interval: int = 60): if not p_instance: return count: int = 0 while psutil.Process(p_instance.pid).status() != psutil.STATUS_ZOMBIE: p_instance.terminate() time.sleep(kill_process_retry_interval) if count % kill_process_retry_interval == 0: print(f'terminating process: {p_name}') count += 1 if count > max_retry: print( f'reach max limitation of retries and failed to terminate process: {p_name}' ) return # clear the zombie p_instance.kill() p_instance = None print(f'{p_name} is terminated')
def kill(process: psutil.Process) -> None: process.kill()
output.close() except Exception as exception: RETCODE -= 100 print(f"Exception occured:\n####\n\n{exception}\n\n####") finally: from psutil import pid_exists, Process while pid_exists(PID): proc = Process(PID) timeout = 5 try: print(f"[{timeout} seconds] Trying to kill process PID: {PID}") proc.kill() proc.wait(timeout) except: pass finally: if pid_exists(PID): try: print( f"[{timeout} seconds] Trying to kill process PID: {PID}" ) proc.terminate() proc.wait(timeout) except: print(f"Process is out of controll PID: {PID}") if stderr is not None: