Created
September 24, 2013 16:37
-
-
Save jizhilong/6687481 to your computer and use it in GitHub Desktop.
how to kill a process's child processes in python
This file contains 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() |
@pcattori impressive usage of contextmanager and psutil 👍
I second that, thank you very much for sharing this, Pedro. We just added your code snippet to a little package we are currently gardening, to make it reusable by others, see pyveci/pueblo#39. We hope you don't have any objections about it. It was the last addition amongst a few updates happening last month, so it just become part of pueblo-0.0.4, also available on PyPI.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Best Solution! thanks!