Skip to content

Instantly share code, notes, and snippets.

@evansd
Created April 9, 2012 21:19
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save evansd/2346614 to your computer and use it in GitHub Desktop.
Save evansd/2346614 to your computer and use it in GitHub Desktop.
Ensure subprocesses exit when their parents die
"""
Utility (Linux only) to ensure subprocesses exit when their parents do by sending
a specified signal when the parent dies.
Usage:
subprocess.Popen(['some-executable'], preexec_fn=on_parent_exit('SIGHUP'))
"""
import signal
from ctypes import cdll
# Constant taken from http://linux.die.net/include/linux/prctl.h
PR_SET_PDEATHSIG = 1
class PrCtlError(Exception):
pass
def on_parent_exit(signame):
"""
Return a function to be run in a child process which will trigger SIGNAME
to be sent when the parent process dies
"""
signum = getattr(signal, signame)
def set_parent_exit_signal():
# http://linux.die.net/man/2/prctl
result = cdll['libc.so.6'].prctl(PR_SET_PDEATHSIG, signum)
if result != 0:
raise PrCtlError('prctl failed with error code %s' % result)
return set_parent_exit_signal
@foxx
Copy link

foxx commented Jun 1, 2013

Outstanding, this worked perfectly first time. I've been looking for a solution to this problem for ages. Thank you so much!

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