-
-
Save youngsofun/11c985d843195b47af15cfea7f42fdb4 to your computer and use it in GitHub Desktop.
how to kill a process's child processes in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import multiprocessing | |
import time | |
import subprocess, os, signal, sys | |
def test(s): | |
while True: | |
print s | |
time.sleep(1.5) | |
def kill_child_processes(signum, frame): | |
parent_id = os.getpid() | |
ps_command = subprocess.Popen("ps -o pid --ppid %d --noheaders" % parent_id, shell=True, stdout=subprocess.PIPE) | |
ps_output = ps_command.stdout.read() | |
retcode = ps_command.wait() | |
for pid_str in ps_output.strip().split("\n")[:-1]: | |
os.kill(int(pid_str), signal.SIGTERM) | |
sys.exit() | |
if __name__ == '__main__': | |
pool = multiprocessing.Pool(processes=4) | |
result = pool.map_async(test, 'abcd') | |
signal.signal(signal.SIGTERM, kill_child_processes) | |
result.get(10000) | |
pool.close() | |
pool.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment