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")
评论列表
文章目录