Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# -*- coding: utf-8 -*- 

2""" 

3@file 

4@brief Helpers about processes. 

5""" 

6from .flog import fLOG 

7 

8 

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. 

15 

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() 

23 

24 def on_terminate(proc): 

25 fLOG("process {} terminated with exit code {}".format(proc, proc.returncode)) 

26 killed.add(proc.pid) 

27 

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 

33 

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("process {} survived SIGTERM; trying SIGKILL".format(p)) 

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("process {} survived SIGKILL; giving up".format(p)) 

50 return killed