kennethreitz-archive / procs

Python, Processes, and Prana.
225 stars 7 forks source link

Nice signal handling? #6

Open hjwp opened 10 years ago

hjwp commented 10 years ago

Here's how you set up a signal handler for the current process, that makes sure any child processes that terminate then properly die (rather than sitting around in "defunct" status leaking resources):

def wait_for_children(signal, stack_frame):
    p = psutil.Process(os.getpid())
    children = p.get_children()
    for child in children:
        try:
            logging.debug('Waiting for child %s' % (child,))
            os.wait4(child.pid, os.WNOHANG)
        except OSError:
            logging.debug('Exception while waiting for child with pid %s' % (child.pid,))

signal.signal(signal.SIGCHLD, wait_for_children)

pretty arcane stuff! there must be a nicer solution...

You can also use signal to special-case ctrl+c, or any other OS signals. This may be too low-level for most users tho, so maybe not such a high priority.

kennethreitz commented 10 years ago

This.