Last active 1695489887

example.py Raw
1import subprocess
2import atexit
3import os
4import 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
9def 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
17def 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:
23run_bash_commands('sleep 10', 'sleep 20')
24