twister: terminate_process: fix NoSuchProcess error

NOTE: Even though previous commits indicate, that this can only happen on
MacOS, that's actually not true. It happens on Linux as well.

The constructor of `psutil.Process` can throw an exception as well, so we
need to wrap the whole loop in another try, unfortunately.

Signed-off-by: Michael Zimmermann <sigmaepsilon92@gmail.com>
This commit is contained in:
Michael Zimmermann 2025-02-19 07:46:17 +01:00 committed by Benjamin Cabé
commit 76b24fac09
2 changed files with 8 additions and 6 deletions

View file

@ -42,9 +42,10 @@ def terminate_process(proc: subprocess.Popen) -> None:
""" """
Try to terminate provided process and all its subprocesses recursively. Try to terminate provided process and all its subprocesses recursively.
""" """
for child in psutil.Process(proc.pid).children(recursive=True): with contextlib.suppress(ProcessLookupError, psutil.NoSuchProcess):
with contextlib.suppress(ProcessLookupError, psutil.NoSuchProcess): for child in psutil.Process(proc.pid).children(recursive=True):
os.kill(child.pid, signal.SIGTERM) with contextlib.suppress(ProcessLookupError, psutil.NoSuchProcess):
os.kill(child.pid, signal.SIGTERM)
proc.terminate() proc.terminate()
# sleep for a while before attempting to kill # sleep for a while before attempting to kill
time.sleep(0.5) time.sleep(0.5)

View file

@ -59,9 +59,10 @@ def terminate_process(proc):
so we need to use try_kill_process_by_pid. so we need to use try_kill_process_by_pid.
""" """
for child in psutil.Process(proc.pid).children(recursive=True): with contextlib.suppress(ProcessLookupError, psutil.NoSuchProcess):
with contextlib.suppress(ProcessLookupError, psutil.NoSuchProcess): for child in psutil.Process(proc.pid).children(recursive=True):
os.kill(child.pid, signal.SIGTERM) with contextlib.suppress(ProcessLookupError, psutil.NoSuchProcess):
os.kill(child.pid, signal.SIGTERM)
proc.terminate() proc.terminate()
# sleep for a while before attempting to kill # sleep for a while before attempting to kill
time.sleep(0.5) time.sleep(0.5)