Coverage for pyquickhelper/loghelper/process_helper.py: 68%
25 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1# -*- coding: utf-8 -*-
2"""
3@file
4@brief Helpers about processes.
5"""
6from .flog import fLOG
9def reap_children(timeout=3, subset=None, fLOG=fLOG):
10 """
11 Terminates children processes.
12 Copied from `psutil <http://psutil.readthedocs.io/en/latest/index.html?highlight=terminate#terminate-my-children>`_.
13 Tries hard to terminate and ultimately
14 kill all the children of this process.
16 @param timeout time out (seconds)
17 @param subset subset of processes to be removed
18 @param fLOG logging function
19 @return killed processes
20 """
21 import psutil
22 killed = set()
24 def on_terminate(proc):
25 fLOG(f"process {proc} terminated with exit code {proc.returncode}")
26 killed.add(proc.pid)
28 procs = psutil.Process().children()
29 if subset is not None:
30 procs = [p for p in procs if p.pid in subset]
31 if len(procs) == 0:
32 return None
34 # send SIGTERM
35 for p in procs:
36 p.terminate()
37 _, alive = psutil.wait_procs(
38 procs, timeout=timeout, callback=on_terminate)
39 if alive:
40 # send SIGKILL
41 for p in alive:
42 fLOG(f"process {p} survived SIGTERM; trying SIGKILL")
43 p.kill()
44 _, alive = psutil.wait_procs(
45 alive, timeout=timeout, callback=on_terminate)
46 if alive:
47 # give up
48 for p in alive:
49 fLOG(f"process {p} survived SIGKILL; giving up")
50 return killed