Skip to content

Instantly share code, notes, and snippets.

@phelian
Last active February 5, 2018 12:57
Show Gist options
  • Save phelian/cb63c83dc9f1df1901a98da98340b5f8 to your computer and use it in GitHub Desktop.
Save phelian/cb63c83dc9f1df1901a98da98340b5f8 to your computer and use it in GitHub Desktop.
Kill child process and n-children processes with python
def kill_child_processes(signum, frame):
"""
SIGTERM override function
Kill running processes childrens and grandchildren before exiting
"""
pid = os.getpid()
kill_processes_recursive(pid)
sys.exit()
def kill_processes_recursive(pid, level=0, maxlvl=2):
"""
List all child processes for current process and kill them, but first call this function for those pids.
"""
if level >= maxlvl:
return
ps_cmd = subprocess.Popen("ps -o pid --ppid {} --noheaders".format(pid), shell=True, stdout=subprocess.PIPE)
ps_output = ps_cmd.stdout.read()
ps_cmd.wait()
cpids = ps_output.strip().split("\n")
for child_pid in cpids:
kill_processes_recursive(child_pid, level=level+1)
if child_pid != "":
try:
os.kill(int(child_pid), signal.SIGTERM)
except OSError:
# If we cant kill a process that does not exist (possibly) then it's fine
pass
Use by: signal.signal(signal.SIGTERM, kill_child_processes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment