本文整理汇总了Python中psutil.wait_procs函数的典型用法代码示例。如果您正苦于以下问题:Python wait_procs函数的具体用法?Python wait_procs怎么用?Python wait_procs使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了wait_procs函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: close
def close(self):
"""Close SSH tunnel."""
logging.debug('Closing tunnel "%s"', self.context.uri)
if self._closed:
return
# Find all ssh instances for user with uri tunnel the hard way...
targets = [
p
for p in psutil.process_iter(attrs=['name', 'username', 'cmdline'])
if p.info['username'] == getpass.getuser()
and p.info['name'] == 'ssh'
and self.context.local_socket in ' '.join(p.info['cmdline'])
] # yapf: disable
# ask nicely for ssh to quit, reap results
for proc in targets:
proc.terminate()
_, alive = psutil.wait_procs(targets, timeout=300)
# kill off the uncooperative, then report any stragglers
for proc in alive:
proc.kill()
_, alive = psutil.wait_procs(targets, timeout=300)
for proc in alive:
logging.info('process %d survived SIGKILL, giving up.', proc.pid)
with suppress(OSError):
os.remove(self.context.local_socket)
self._closed = True
示例2: stop
def stop(self):
"""Stop the daemon."""
pid = self.get_pid()
if os.path.exists(self.pid_file):
os.remove(self.pid_file)
if pid is None:
return
elif psutil.pid_exists(pid):
parent = psutil.Process(pid)
if parent.name() == self.pid_name:
procs = parent.children(recursive=True)
procs.append(parent)
for p in procs:
p.terminate()
gone, alive = psutil.wait_procs(procs, timeout=3)
if alive:
for p in alive:
p.kill()
gone, alive = psutil.wait_procs(alive, timeout=3)
if alive:
for p in alive:
message = "Process {0} survived SIGKILL"
sys.stderr.write(message.format(p))
示例3: matar_procesos
def matar_procesos(pid):
parent = psutil.Process(pid)
children = parent.get_children(recursive=True)
for child in children:
child.kill()
psutil.wait_procs(children, timeout=5)
示例4: reap_children
def reap_children(search_all=False):
"""Kill any subprocess started by this test suite and ensure that
no zombies stick around to hog resources and create problems when
looking for refleaks.
"""
global _subprocesses_started
procs = _subprocesses_started.copy()
if search_all:
this_process = psutil.Process()
for p in this_process.children(recursive=True):
procs.add(p)
for p in procs:
try:
p.terminate()
except psutil.NoSuchProcess:
pass
gone, alive = psutil.wait_procs(procs, timeout=GLOBAL_TIMEOUT)
for p in alive:
warn("couldn't terminate process %s" % p)
try:
p.kill()
except psutil.NoSuchProcess:
pass
_, alive = psutil.wait_procs(alive, timeout=GLOBAL_TIMEOUT)
if alive:
warn("couldn't not kill processes %s" % str(alive))
_subprocesses_started = set(alive)
示例5: terminate_all_children
def terminate_all_children():
""" Terminates all children """
logger.debug("Terminating Process...")
print("Terminating Process...", flush=True)
children = psutil.Process().children(recursive=True)
for child in children:
child.terminate()
_, alive = psutil.wait_procs(children, timeout=10)
if not alive:
logger.debug("Terminated")
print("Terminated")
return
logger.debug("Termination timed out. Killing Process...")
print("Termination timed out. Killing Process...", flush=True)
for child in alive:
child.kill()
_, alive = psutil.wait_procs(alive, timeout=10)
if not alive:
logger.debug("Killed")
print("Killed")
else:
for child in alive:
msg = "Process {} survived SIGKILL. Giving up".format(child)
logger.debug(msg)
print(msg)
示例6: reap
def reap(process, timeout=3):
"Tries hard to terminate and ultimately kill all the children of this process."
def on_terminate(proc):
print("process {} terminated with exit code {}".format(proc.pid, proc.returncode))
try:
procs = process.children(recursive=True)
# send SIGTERM
for p in procs:
print("Killing ", p.pid)
p.terminate()
gone, alive = psutil.wait_procs(procs, timeout=timeout, callback=on_terminate)
if alive:
# send SIGKILL
for p in alive:
print("process {} survived SIGTERM; trying SIGKILL" % p.pid)
p.kill()
gone, alive = psutil.wait_procs(alive, timeout=timeout, callback=on_terminate)
if alive:
# give up
for p in alive:
print("process {} survived SIGKILL; giving up" % p.pid)
print("Killing ", process.pid)
process.kill()
except:
print("Killing failed; assuming process exited early.")
示例7: end
def end(self):
"""
Terminate (and then kill) the manager process launched.
:return:
"""
if not self._process:
self.log.warn('Ending without manager process.')
return
this_process = psutil.Process(os.getpid())
try:
manager_process = psutil.Process(self._process.pid)
except psutil.NoSuchProcess:
self.log.info("Manager process not running.")
return
# First try SIGTERM
if manager_process.is_running() \
and manager_process.pid in [x.pid for x in this_process.children()]:
self.log.info("Terminating manager process: %s", manager_process.pid)
manager_process.terminate()
# TODO: Remove magic number
timeout = 5
self.log.info("Waiting up to %ss for manager process to exit...", timeout)
try:
psutil.wait_procs({manager_process}, timeout)
except psutil.TimeoutExpired:
self.log.debug("Ran out of time while waiting for "
"processes to exit")
# Then SIGKILL
if manager_process.is_running() \
and manager_process.pid in [x.pid for x in this_process.children()]:
self.log.info("Killing manager process: %s", manager_process.pid)
manager_process.kill()
manager_process.wait()
示例8: reap_children
def reap_children(recursive=False):
"""Terminate and wait() any subprocess started by this test suite
and ensure that no zombies stick around to hog resources and
create problems when looking for refleaks.
If resursive is True it also tries to terminate and wait()
all grandchildren started by this process.
"""
# Get the children here, before terminating the children sub
# processes as we don't want to lose the intermediate reference
# in case of grandchildren.
if recursive:
children = psutil.Process().children(recursive=True)
else:
children = []
# Terminate subprocess.Popen instances "cleanly" by closing their
# fds and wiat()ing for them in order to avoid zombies.
subprocs = _subprocesses_started.copy()
_subprocesses_started.clear()
for subp in subprocs:
try:
subp.terminate()
except OSError as err:
if err.errno != errno.ESRCH:
raise
if subp.stdout:
subp.stdout.close()
if subp.stderr:
subp.stderr.close()
try:
# Flushing a BufferedWriter may raise an error.
if subp.stdin:
subp.stdin.close()
finally:
# Wait for the process to terminate, to avoid zombies.
try:
subp.wait()
except OSError as err:
if err.errno != errno.ECHILD:
raise
# Terminates grandchildren.
if children:
for p in children:
try:
p.terminate()
except psutil.NoSuchProcess:
pass
gone, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT)
for p in alive:
warn("couldn't terminate process %r; attempting kill()" % p)
try:
p.kill()
except psutil.NoSuchProcess:
pass
_, alive = psutil.wait_procs(alive, timeout=GLOBAL_TIMEOUT)
if alive:
for p in alive:
warn("process %r survived kill()" % p)
示例9: kill_process_tree
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")
示例10: kill_children
def kill_children(self, parent_pid, sig=signal.SIGINT):
"""Kill all OWTF child process when the SIGINT is received
:param parent_pid: The pid of the parent OWTF process
:type parent_pid: `int`
:param sig: Signal received
:type sig: `int`
:return:
:rtype: None
"""
def on_terminate(proc):
"""Log debug info on child process termination
:param proc: Process pid
:rtype: None
"""
logging.debug("Process {} terminated with exit code {}".format(proc, proc.returncode))
parent = psutil.Process(parent_pid)
children = parent.children(recursive=True)
for child in children:
child.send_signal(sig)
_, alive = psutil.wait_procs(children, callback=on_terminate)
if not alive:
# send SIGKILL
for pid in alive:
logging.debug("Process {} survived SIGTERM; trying SIGKILL" % pid)
pid.kill()
_, alive = psutil.wait_procs(alive, callback=on_terminate)
if not alive:
# give up
for pid in alive:
logging.debug("Process {} survived SIGKILL; giving up" % pid)
示例11: _abort
def _abort(self):
"""
Terminate all live jobs.
"""
for i, (slot, proc) in enumerate(zip(self._slots, self._procs)):
if slot:
if not is_windows:
try:
os.killpg(proc.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(proc.pid, signal.SIGTERM)
except OSError:
pass
else:
root_proc = psutil.Process(proc.pid)
children = root_proc.children(recursive=True) + [root_proc]
for child_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(child_proc.pid, signal.SIGTERM)
except OSError:
pass
psutil.wait_procs(children, timeout=1)
self._slots[i], self._procs[i] = 0, None
示例12: watch_process
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)
示例13: run
def run(self):
running=True;
cpu = [];
mem = [];
x = [];
z = []
d = 0.0;
p = self.proc;
i0 = [];
i1 = [];
i2 = [];
i3 = [];
try:
while d<self.totaltime:
d += 1;
if p.status!='zombie':
# If the program is running, this captures
# the vital-statistics.
cpu.append(p.get_cpu_percent());
mem.append(p.get_memory_percent());
z.append(p.get_cpu_times().system)
x.append(d)
i0.append([p.get_io_counters()[0]])
i1.append([p.get_io_counters()[1]])
i2.append([p.get_io_counters()[2]])
i3.append([p.get_io_counters()[3]])
else:
# This watches and ensures that the
# process is indeed dead. This is the first
# level of exception handling and
# loop-breakage.
procs = psutil.get_process_list();
gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
break
time.sleep(1)
except psutil._error.AccessDenied:
# This exception watches for the natural death of the
# process. This is the second level of redundancy handling
# the death of the task, the first one is in the else
# statement above.
p.kill()
print "It has died and has become a... "+p.status;
procs = psutil.get_process_list();
gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
except KeyboardInterrupt:
# This exception allows the user to exit the watch. You
# have to terminate the process elsewhere.
print "Exiting..."+p.status
procs = psutil.get_process_list();
gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
self.cpu = pl.array(cpu);
self.x = pl.array(x);
self.ram = pl.array(mem);
self.z = pl.array(z);
self.i0 = pl.array(i0);
self.i1 = pl.array(i1);
self.i2 = pl.array(i2);
self.i3 = pl.array(i3);
示例14: kill_process_tree
def kill_process_tree(pid, timeout=3):
"""Kill a hierarchy of processes.
:param pid: pid of the toplevel process
:type pid: int | psutil.Process
:return: True if all processes either don't exist or have been killed,
False if there are some processes still alive.
:rtype: bool
"""
import psutil
if isinstance(pid, psutil.Process):
parent_process = pid
else:
try:
parent_process = psutil.Process(pid)
except psutil.NoSuchProcess as err:
e3.log.debug(err)
return True
logger.debug('kill_process_tree %s', parent_process)
def kill_process(proc):
"""Kill a process, catching all psutil exceptions.
:param proc: process to kill
:type proc: psutil.Process
"""
try:
logger.debug('kill_process_tree %s', pid)
proc.kill()
logging.info('%s process killed pid:%s (%s)',
'parent' if proc.pid == pid else 'child',
proc.pid,
proc.cmdline())
except psutil.Error as err:
e3.log.debug(err)
pass
try:
children = parent_process.children(recursive=True)
except psutil.NoSuchProcess as err:
e3.log.debug(err)
return True
# Kill the parent first to not let him spawn new child processes
kill_process(parent_process)
for child_process in children:
kill_process(child_process)
try:
psutil.wait_procs(children, timeout=timeout)
parent_process.wait(timeout=timeout)
return True
except psutil.TimeoutExpired as err:
e3.log.debug(err)
return False
示例15: kill_proc_tree
def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
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)