Greg Greg - 18 days ago 5
Python Question

Python subprocess - check exit codes of forked program

Say I have a script like this:

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


And then forked_job.py looks like this:

import os
import sys

print 'hi'
pid = os.fork()
if pid == 0:
sys.exit(do_some_work())
else:
sys.exit(do_other_work())


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

Answer

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:

os.wait()

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:

    main_script
     /       \
forked_job   forked_job

But instead:

        main_script
            |
      forked_job_parent
            |
       forked_job_child

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