Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
giampaolo opened this issue May 23, 2014 · 2 comments
Closed

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

giampaolo opened this issue May 23, 2014 · 2 comments

Comments

@giampaolo
Copy link
Owner

From g.rodola on October 09, 2013 15:14:54

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: http://code.google.com/p/psutil/issues/detail?id=440

@giampaolo giampaolo self-assigned this May 23, 2014
@giampaolo
Copy link
Owner Author

From g.rodola on October 09, 2013 12:36:31

Implemented in revision 4906c5c4e5ba .

Status: FixedInHG

@giampaolo
Copy link
Owner Author

From g.rodola on November 20, 2013 12:33:07

Fixed in version 1.2.0 which I released a moment ago.

Status: Fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant