kiranvizru / psutil

Automatically exported from code.google.com/p/psutil
Other
0 stars 0 forks source link

Provide an API to wait for multiple processes to terminate #440

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
This would serve the following use case:

 * we have a list of processes we want to terminate
 * send them SIGTERM (via Process.terminate())
 * give them some time to terminate (say 3 seconds)
 * figure out which ones are terminated and which ones are not
 * for those ones which are not send SIGKILL as last resort (via Process.kill())
 * wait again and in case they are still alive just give up

If we'd have to do this for a single process psutil already provides all the 
necessary hooks:

p.terminate()
try:
    p.wait(timeout=3)
except psutil.TimeoutExpired:
    p.kill()
    try:
        p.wait(timeout=3)
    except psutil.TimeoutExpired:
        sys.exit('giving up')

When it comes to do the same thing for a *list* of processes it is not 
immediately clear how to do this right.
We can introduce a new psutil.wait_procs(plist, timeout, callback=None) utility 
function which:

* waits for a list of processes 'plist' to terminate and return a (gone, 
still_alive) tuple
* gone and still_alive are lists of Process instances
* Process instances in the 'gone' list will have a new 'retcode' attribute 
attached to them 
* 'callback' kwarg, if specified, will be called with a 'proc' argument as soon 
as a process terminates

Code sample:

def on_terminate(proc):
    print("process {} terminated".format(proc))

def on_kill(proc):
    print("process {} killed".format(proc))

for p in procs:
    p.terminate()
gone, alive = psutil.wait_procs(procs, 3, callback=on_terminate)
if alive:
    for p in alive:
        p.kill()
    gone, alive = psutil.wait_procs(procs, 3, callback=on_kill)
    for p in alive:
        print("could not kill process {}".format(p))

Original issue reported on code.google.com by g.rodola on 9 Oct 2013 at 1:14

GoogleCodeExporter commented 9 years ago
Implemented in revision 4906c5c4e5ba.

Original comment by g.rodola on 9 Oct 2013 at 7:36

GoogleCodeExporter commented 9 years ago
Fixed in version 1.2.0 which I released a moment ago.

Original comment by g.rodola on 20 Nov 2013 at 8:33