Greg Greg - 2 months ago 8
Python Question

Python subprocess - check exit codes of forked program

Say I have a script like this:

p = subprocess.Popen(['python'], shell=True)
status = p.wait()
# Do something with status

And then looks like this:

import os
import sys

print 'hi'
pid = os.fork()
if pid == 0:

How can I make sure both processes return a 0 status code?


When you fork, you have a parent and a non-parent process. When pid == 0, you are in the child process; your else statement is when you're within the parent process.

Similar to calling Popen.wait, as you do in the first script, you want to call os.wait in the second one.

From the docs:


Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

Availability: Unix

As you can see, this of course assumes that you're running unix. Since os.fork is also Unix-only, this seems likely.

So, have the parent call os.wait and reflect the status back up in what the parent returns.

One thing to note, though it probably doesn't matter, and you're probably aware. You're technically not doing this:

     /       \
forked_job   forked_job

But instead:


(I'm attempting to show the "ownership", and hence the usage of the second wait.)