我们从Python开源项目中,提取了以下26个代码示例,用于说明如何使用psutil.wait_procs()。
def kill_proc(proc): """ Kill a process and its children processes :param proc: Process class defined in psutil :return: None """ try: children = proc.children() for child in children: try: child.terminate() except: pass gone, still_alive = psutil.wait_procs(children, timeout=3) for p in still_alive: p.kill() proc.kill() except: pass
def _terminate(self): if self.process is None: return try: parent = psutil.Process(pid=self.process.pid) procs = parent.children(recursive=True) procs.append(parent) for proc in procs: proc.terminate() gone, still_alive = psutil.wait_procs( procs, timeout=constants.POPEN_TERM_TIMEOUT) for proc in still_alive: proc.kill() except OSError as exc: if exc.errno != errno.ESRCH: # ESRCH -> process doesn't exist (already ended) raise exc except psutil.NoSuchProcess: pass # probably ended already
def signal_handler(sig, frame): """Handles signals sent by the user. In the case the SIGINT signal is received, child processes will be stopped. """ if sig == signal.SIGINT: print(bcolors.OKBLUE + "\n[-] The program is stopping..." + bcolors.ENDC) procs = psutil.Process().children(recursive=True) try: for p in procs: p.terminate() gone, still_alive = psutil.wait_procs(psutil.Process().children(recursive=True), timeout=3) for p in still_alive: p.kill() except: pass sys.exit(0)
def wait_for_all(exe, timeout=30): """Wait for the given process to exit""" import psutil processes = [] for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'exe']) except psutil.NoSuchProcess: pass else: if 'exe' in pinfo and pinfo['exe'] is not None and\ os.path.basename(pinfo['exe']) == exe: processes.append(proc) if len(processes): logging.debug("Waiting up to %d seconds for %s to exit", timeout, exe) psutil.wait_procs(processes, timeout=timeout)
def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True, timeout=None, on_terminate=None): """Kill a process tree (including grandchildren) with signal "sig" and return a (gone, still_alive) tuple. "on_terminate", if specified, is a callabck function which is called as soon as a child terminates. """ if pid == os.getpid(): raise RuntimeError("I refuse to kill myself") parent = psutil.Process(pid) children = parent.children(recursive=True) if include_parent: children.append(parent) for p in children: p.send_signal(sig) gone, alive = psutil.wait_procs(children, timeout=timeout, callback=on_terminate) return (gone, alive)
def kill_proc_tree(self, _pid, including_parent=True): parent = psutil.Process(_pid) children = [] children = parent.children(recursive=True) for child in children: child.kill() psutil.wait_procs(children, timeout=5) if including_parent: if psutil.pid_exists(parent.pid): parent.kill() parent.wait(5) ## Callback function that is executed after a process is completed # A status file is generated that contains the return code of the executed process # @param _path path where the processes was started # @param _return_code return code of completed process
def stop(self, force=False): if self.process is not None: if not force: msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle('Confirm process termination') msg.setText( 'This will terminate the running process. Are you sure ' 'you want to do this?') msg.setInformativeText( 'Interrupting the process may leave partly ' 'created files that cannot be used for ' 'further analysis.') msg.addButton('Stop process', QMessageBox.YesRole) cancel_button = msg.addButton('Cancel', QMessageBox.NoRole) msg.setDefaultButton(cancel_button) msg.exec_() if msg.clickedButton() == cancel_button: # Continue to run return self._interrupted = True # Terminate child processes as well pid = int(self.process.pid()) if sys.platform == 'win32' and pid != 0: # The returned value is not a PID but a pointer lp = ctypes.cast(pid, LPWinProcInfo) pid = lp.contents.dwProcessID if pid != 0: process = psutil.Process(pid) children = process.children(recursive=True) for proc in children: proc.terminate() gone, alive = psutil.wait_procs(children, timeout=3) for proc in alive: proc.kill() self.process.terminate() self.process = None
def kill (pid, including_parent = True): try: parent = psutil.Process(pid) except psutil.NoSuchProcess: return children = parent.children(recursive=True) for child in children: child.kill() psutil.wait_procs(children, timeout=5) if including_parent: parent.kill() parent.wait(5)
def stop(self): # Java forks internally and detaches its children, use psutil to hunt # them down and kill them proc = psutil.Process(self.proc.pid) processes = [proc] + proc.children(recursive=True) # Be nice to begin with for p in processes: p.terminate() _, alive = psutil.wait_procs(processes, timeout=3) # But if they aren't, we can be more persuasive for p in alive: p.kill() psutil.wait_procs(alive, timeout=3)
def test_wait_procs_no_timeout(self): sproc1 = get_test_subprocess() sproc2 = get_test_subprocess() sproc3 = get_test_subprocess() procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)] for p in procs: p.terminate() gone, alive = psutil.wait_procs(procs)
def _terminate(self, pid): procs = Process(pid).children() for p in procs: p.terminate() gone, still_alive = wait_procs(procs, timeout=1, callback=self._on_terminate) for p in still_alive: p.kill()
def kill_process_tree(pid): try: main_proc = psutil.Process(pid) except (psutil.NoSuchProcess, psutil.AccessDenied) as ex: return processes = main_proc.children(recursive=True) processes.append(main_proc) for proc in processes: proc.terminate() psutil.wait_procs(processes)
def _abort(self): """Terminate all live jobs.""" for i, pid in enumerate(self._slots): if pid != 0: if not is_windows: try: os.killpg(pid, signal.SIGTERM) except OSError: # If the process with pid did not have time to become a process group leader, # then pgid does not exist and os.killpg could not kill the process, # so re-try kill the process only. try: os.kill(pid, signal.SIGTERM) except OSError: pass else: root_proc = psutil.Process(pid) children = root_proc.children(recursive=True) + [root_proc] for proc in children: try: # Would be easier to use proc.terminate() here but psutils # (up to version 5.4.0) on Windows terminates processes with # the 0 signal/code, making the outcome of the terminated # process indistinguishable from a successful execution. os.kill(proc.pid, signal.SIGTERM) except OSError: pass psutil.wait_procs(children, timeout=1) self._slots[i] = 0
def watch_process(self): """ Watcher thread. This one relaunches airodump eatch time it dies until we call stop() """ psutil.wait_procs([psutil.Process(self._proc.pid)], callback=self.start)
def watch_process(self): """ Watcher thread. This one relaunches airodump eatch time it dies until we call stop() """ try: psutil.wait_procs([psutil.Process(self._proc.pid)], callback=self.start) except psutil. NoSuchProcess: pass
def kill_process_tree(pid, including_parent=True): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() gone, still_alive = psutil.wait_procs(children, timeout=5) if including_parent: parent.kill() parent.wait(5)
def kill_proc_tree(pid, including_parent=False): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() gone, still_alive = psutil.wait_procs(children, timeout=5)
def kill_proc_tree(pid, including_parent=True): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() gone, still_alive = psutil.wait_procs(children, timeout=5) if including_parent: parent.kill() parent.wait(5)
def kill_process_tree(logger, pid, timeout=DEFAULT_TIME_TO_WAIT_AFTER_SIGTERM): """ TODO(saguziel): also kill the root process after killing descendants Kills the process's descendants. Kills using the `kill` shell command so that it can change users. Note: killing via PIDs has the potential to the wrong process if the process dies and the PID gets recycled in a narrow time window. :param logger: logger :type logger: logging.Logger """ try: root_process = psutil.Process(pid) except psutil.NoSuchProcess: logger.warning("PID: {} does not exist".format(pid)) return # Check child processes to reduce cases where a child process died but # the PID got reused. descendant_processes = [x for x in root_process.children(recursive=True) if x.is_running()] if len(descendant_processes) != 0: logger.info("Terminating descendant processes of {} PID: {}" .format(root_process.cmdline(), root_process.pid)) temp_processes = descendant_processes[:] for descendant in temp_processes: logger.info("Terminating descendant process {} PID: {}" .format(descendant.cmdline(), descendant.pid)) if not kill_using_shell(logger, descendant.pid, signal.SIGTERM): descendant_processes.remove(descendant) logger.info("Waiting up to {}s for processes to exit..." .format(timeout)) try: psutil.wait_procs(descendant_processes, timeout) logger.info("Done waiting") except psutil.TimeoutExpired: logger.warning("Ran out of time while waiting for " "processes to exit") # Then SIGKILL descendant_processes = [x for x in root_process.children(recursive=True) if x.is_running()] if len(descendant_processes) > 0: temp_processes = descendant_processes[:] for descendant in temp_processes: logger.info("Killing descendant process {} PID: {}" .format(descendant.cmdline(), descendant.pid)) if not kill_using_shell(logger, descendant.pid, signal.SIGKILL): descendant_processes.remove(descendant) else: descendant.wait() logger.info("Killed all descendant processes of {} PID: {}" .format(root_process.cmdline(), root_process.pid)) else: logger.debug("There are no descendant processes to kill")
def test_wait_procs(self): def callback(p): l.append(p.pid) l = [] sproc1 = get_test_subprocess() sproc2 = get_test_subprocess() sproc3 = get_test_subprocess() procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)] self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1) self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1) t = time.time() gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback) self.assertLess(time.time() - t, 0.5) self.assertEqual(gone, []) self.assertEqual(len(alive), 3) self.assertEqual(l, []) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 1) self.assertEqual(len(alive), 2) return gone, alive sproc3.terminate() gone, alive = test(procs, callback) self.assertIn(sproc3.pid, [x.pid for x in gone]) if POSIX: self.assertEqual(gone.pop().returncode, signal.SIGTERM) else: self.assertEqual(gone.pop().returncode, 1) self.assertEqual(l, [sproc3.pid]) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 3) self.assertEqual(len(alive), 0) return gone, alive sproc1.terminate() sproc2.terminate() gone, alive = test(procs, callback) self.assertEqual(set(l), set([sproc1.pid, sproc2.pid, sproc3.pid])) for p in gone: self.assertTrue(hasattr(p, 'returncode'))
def test_wait_procs(self): def callback(p): l.append(p.pid) l = [] sproc1 = get_test_subprocess() sproc2 = get_test_subprocess() sproc3 = get_test_subprocess() procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)] self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1) self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1) t = time.time() gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback) self.assertLess(time.time() - t, 0.5) self.assertEqual(gone, []) self.assertEqual(len(alive), 3) self.assertEqual(l, []) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 1) self.assertEqual(len(alive), 2) return gone, alive sproc3.terminate() gone, alive = test(procs, callback) self.assertIn(sproc3.pid, [x.pid for x in gone]) if POSIX: self.assertEqual(gone.pop().returncode, -signal.SIGTERM) else: self.assertEqual(gone.pop().returncode, 1) self.assertEqual(l, [sproc3.pid]) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 3) self.assertEqual(len(alive), 0) return gone, alive sproc1.terminate() sproc2.terminate() gone, alive = test(procs, callback) self.assertEqual(set(l), set([sproc1.pid, sproc2.pid, sproc3.pid])) for p in gone: self.assertTrue(hasattr(p, 'returncode'))
def test_wait_procs(self): def callback(p): pids.append(p.pid) pids = [] sproc1 = get_test_subprocess() sproc2 = get_test_subprocess() sproc3 = get_test_subprocess() procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)] self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1) self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1) t = time.time() gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback) self.assertLess(time.time() - t, 0.5) self.assertEqual(gone, []) self.assertEqual(len(alive), 3) self.assertEqual(pids, []) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 1) self.assertEqual(len(alive), 2) return gone, alive sproc3.terminate() gone, alive = test(procs, callback) self.assertIn(sproc3.pid, [x.pid for x in gone]) if POSIX: self.assertEqual(gone.pop().returncode, -signal.SIGTERM) else: self.assertEqual(gone.pop().returncode, 1) self.assertEqual(pids, [sproc3.pid]) for p in alive: self.assertFalse(hasattr(p, 'returncode')) @retry_before_failing(30) def test(procs, callback): gone, alive = psutil.wait_procs(procs, timeout=0.03, callback=callback) self.assertEqual(len(gone), 3) self.assertEqual(len(alive), 0) return gone, alive sproc1.terminate() sproc2.terminate() gone, alive = test(procs, callback) self.assertEqual(set(pids), set([sproc1.pid, sproc2.pid, sproc3.pid])) for p in gone: self.assertTrue(hasattr(p, 'returncode'))