os.system() or os.execv() w/stdout redirect and PID tracking

Donn Cave donn at u.washington.edu
Fri May 7 12:46:53 EDT 1999


Michael Olivier <dmtech at iname.com> writes:
...
| Thanks a lot, Gordon!  This really helps.  It took a little to
| understand the magic hacks going on... is there any cleaner way to refer
| to stdout than as '1'?  I'm also trapping stderr as '2' ... and I
| modified for the output to go to a file I open instead of piped back to
| the original process.

You can't get any cleaner than 1.  1 (like any file descriptor) is the
real thing - an abstraction like stdout that supports device independent
I/O operations, but is unburdened by the complications of a C library
process-internal buffer.  It's brilliantly simple, especially on UNIX
where it's consistently implemented.  (Some systems hack in a device,
like the socket in particular, as an afterthought without integrating
it as a true file descriptor, sort of missing the point.)

| You close stdout with os.close(1) -- os.dup() then just happens to fill
| in the stdout slot in the table because it's available? Scary coding if
| true, but if it gets me what I need... how much can I count on this
| staying the same for future Linux & Sun implementations?

It's a given, but as Gordon already allowed in a followup, you could as
well use dup2() to say exactly what you want.  You're right about how
the slot works, so the burden of dup() is that you have to account for
0 as well as 1, i.e., all the units below the slot you're aiming at.

These are (normally?) both covers for the F_DUPFD fcntl(), which works
like this:

    newfd = fcntl.fcntl(oldfd, FCNTL.F_DUPFD, lowfd)
    assert newfd >= lowfd

I understand all three of these functions appear in the XPG4 standard,
but I don't think they're in POSIX 1003.1.  Some information here that
probably no one wanted, but hoping that a little light shed on these
things will dispell the aura of magic.

Maybe a better way to say it: Yes, these are low level primitives in the
sense that stdio etc. build on top of them, but on the other hand they're
very high level abstractions that are there for your direct use too.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list