os.fork()

beej at piratehaven.org beej at piratehaven.org
Mon Dec 24 11:49:51 EST 2001


In article <3C26FD03.4050301 at beth.uniforum.org.za>,
mixo  <mixo at beth.uniforum.org.za> wrote:
>What does 'os.fork' return?

To the parent process, it returns the child's PID.  To the child, it
returns 0.

To get the exit status of the child, you have to have the parent
os.wait() for it to complete.  (Also see os.waitpid()).

Here's a barebones example with really bad error checking:

import os

pid = os.fork()
if pid == 0:
    print "I'm the child, and my pid is %d!" % (os.getpid())
    os._exit(2)
else:
    print "I'm the parent, and I just forked pid %d!" % (pid)
    (rpid, status) = os.wait() # reap the zombie child
    print "I'm the parent, and my child %d exited with status %d" % \
        (rpid, os.WEXITSTATUS(status))

-Beej




More information about the Python-list mailing list