example.py
Raw
import subprocess
import atexit
import os
import signal
# 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.
def run_bash_commands(cmd1, cmd2):
# Start the bash processes
process1 = subprocess.Popen(cmd1, shell=True, preexec_fn=os.setsid)
process2 = subprocess.Popen(cmd2, shell=True, preexec_fn=os.setsid)
# Register a cleanup function to be called when the script exits
atexit.register(cleanup, process1, process2)
def cleanup(process1, process2):
# Kill the bash processes
os.killpg(os.getpgid(process1.pid), signal.SIGTERM)
os.killpg(os.getpgid(process2.pid), signal.SIGTERM)
# Example usage:
run_bash_commands('sleep 10', 'sleep 20')
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. |
7 | # This allows us to kill the processes and all their child processes (if any) by sending a signal to the process group. |
8 | |
9 | def run_bash_commands(cmd1, cmd2): |
10 | # Start the bash processes |
11 | process1 = subprocess.Popen(cmd1, shell=True, preexec_fn=os.setsid) |
12 | process2 = subprocess.Popen(cmd2, shell=True, preexec_fn=os.setsid) |
13 | |
14 | # Register a cleanup function to be called when the script exits |
15 | atexit.register(cleanup, process1, process2) |
16 | |
17 | def cleanup(process1, process2): |
18 | # Kill the bash processes |
19 | os.killpg(os.getpgid(process1.pid), signal.SIGTERM) |
20 | os.killpg(os.getpgid(process2.pid), signal.SIGTERM) |
21 | |
22 | # Example usage: |
23 | run_bash_commands('sleep 10', 'sleep 20') |
24 |