ToughMind
ToughMind

Reputation: 1009

[Windows,python]How to make process started by subprocee.Popen() to automatically terminate when the parent process is dead?

In my python script, I started some process using:

p1 = subprocess.Popen('p1.exe')
p2 = subprocess.Popen('p2.exe')

When those two subprocess started, they won't be killed when the parent process is dead because some error.
I want those three process, the parent process, p1 and p2 to exit at the same time. That is any of them terminated makes all others terminated. How could I manage this on Windows? What about Linux?

Upvotes: 0

Views: 60

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155418

Assuming the parent process is dying from an exception (rather than some hard error like a segmentation fault), a simple try/finally can guarantee a process is terminated when the block is exited (by execution running off the end, exceptions bubbling out, return leaving the function early, etc.):

p1 = p2 = None  # Ensure names exist
try:
    p1 = subprocess.Popen('p1.exe')
    p2 = subprocess.Popen('p2.exe')
    # ... stuff that runs in tandem with processes

finally:
    for p in (p1, p2):
        if p is not None:
            p.terminate()

If you want the child processes to close more cleanly, a simple with statement will suffice (the std handles will be closed, and you'll wait on each process):

with subprocess.Popen('p1.exe') as p1, subprocess.Popen('p2.exe') as p2:
    # ... stuff that runs in tandem with processes

If the processes are to be launched, and run as long as the parent process is up, you'd instead use the atexit module to register them for termination when the main process is exiting:

import atexit

p1 = subprocess.Popen('p1.exe')
atexit.register(p1.terminate)
p2 = subprocess.Popen('p2.exe')
atexit.register(p2.terminate)
# ... rest of your code

Upvotes: 1

Related Questions