fork & exec a process?

Donn Cave donn at drizzle.com
Mon Nov 26 12:33:19 EST 2001


Quoth Jim Meier <jim at home.com>:

| I'm trying to fork & exec a process, and be able to read it's output
| to stderr and stdout. 
...
| I've also tried a popen trick as mentioned in that file, of opening a
| pipe and using popen with redirection to it;
|
| out_read, out_write = os.pipe()
| err_read, err_write = os.pipe()
| ret = os.popen("command >&%d 2>&%d" % (out_write, err_write))

That's kind of an awkward way to do it, and I'm kind of surprised
it works - I would have guessed popen(3) would close the parent's
file descriptors in the fork.  Like another poster already, I would
suggest something from the popen2 module.

| and then reading from out_read and err_read. The problem with this
| approach is that i can't tell when the process dies - except by
| calling ret.close(), and blocking until it does close.
|
| The purpose of all this is to execute some long-running programs (like
| ping) and collect their results, while still processing the rest of
| what needs to be done.

If you look at the popen2 module (it's written in Python), you will
see it doing a lot of close()s.  When every last process closes the
write end of a pipe, its readers see end-of-file.  That's the simple
way to know when the other end dies - if you haven't kept an open write
end yourself.  Of course end of file yields an empty string.

Your other problem is that it might still be alive.  If you have read
all its output and come back for more, you'll block until it writes
more.  I would use select() for that, and I would use file descriptors
(from_child.fileno()) and os.read with the pipes.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list