Tough Spawn Problem

Jeff Epler jepler at unpythonic.net
Sun Mar 6 09:04:09 EST 2005


By using os.spawn* and the os.P_NOWAIT, the spawn function will return
immediately, with the return value being the PID of the new process.
Later, you can use os.kill() to force the program to terminate,
os.waitpid() to retrieve the exit status if it has terminated, or you
could use the signal module to wait for SIGCHLD to be delivered at the
time the child terminates.

With os.spawn*, the child's open files (including stdin and stdout) are
the same as the parent's; using the popen2 module, you can send the
program input and capture its output too.

Here's the program I ran on Linux (Fedora Core 2 / Python 2.3) to show
that os.P_NOWAIT works fine:
    import os
    pid = os.spawnv(os.P_NOWAIT, "/bin/sh",
                        ["sh", "-c", "sleep 1; echo spawned program"])
    print "child is pid", pid
    print "waitpid result is", os.waitpid(pid, 0)
and the output is
    $ python /tmp/googlemike.py 
    child is pid 13874
    spawned program
    waitpid result is (13874, 0)
the fact that "spawned program" is printed after "child is pid NNNNN"
shows that the python program continues executing while the child is
working (or, in this case, sleeping).

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050306/b75c1703/attachment.sig>


More information about the Python-list mailing list