cyberes revised this gist . Go to revision
1 file changed, 2 insertions, 1 deletion
example.py
@@ -3,7 +3,8 @@ import atexit | |||
3 | 3 | import os | |
4 | 4 | import signal | |
5 | 5 | ||
6 | - | # The preexec_fn=os.setsid argument in the Popen calls is used to start the bash processes in new process groups. This allows us to kill the processes and all their child processes (if any) by sending a signal to the process group. | |
6 | + | # The preexec_fn=os.setsid argument in the Popen calls is used to start the bash processes in new process groups. | |
7 | + | # This allows us to kill the processes and all their child processes (if any) by sending a signal to the process group. | |
7 | 8 | ||
8 | 9 | def run_bash_commands(cmd1, cmd2): | |
9 | 10 | # Start the bash processes |
cyberes revised this gist . Go to revision
1 file changed, 22 insertions
example.py(file created)
@@ -0,0 +1,22 @@ | |||
1 | + | import subprocess | |
2 | + | import atexit | |
3 | + | import os | |
4 | + | import signal | |
5 | + | ||
6 | + | # The preexec_fn=os.setsid argument in the Popen calls is used to start the bash processes in new process groups. This allows us to kill the processes and all their child processes (if any) by sending a signal to the process group. | |
7 | + | ||
8 | + | def run_bash_commands(cmd1, cmd2): | |
9 | + | # Start the bash processes | |
10 | + | process1 = subprocess.Popen(cmd1, shell=True, preexec_fn=os.setsid) | |
11 | + | process2 = subprocess.Popen(cmd2, shell=True, preexec_fn=os.setsid) | |
12 | + | ||
13 | + | # Register a cleanup function to be called when the script exits | |
14 | + | atexit.register(cleanup, process1, process2) | |
15 | + | ||
16 | + | def cleanup(process1, process2): | |
17 | + | # Kill the bash processes | |
18 | + | os.killpg(os.getpgid(process1.pid), signal.SIGTERM) | |
19 | + | os.killpg(os.getpgid(process2.pid), signal.SIGTERM) | |
20 | + | ||
21 | + | # Example usage: | |
22 | + | run_bash_commands('sleep 10', 'sleep 20') |