This feels like a FAQ but I've been reading here a while and haven't
seen it, and it doesn't seem to appear in the standard FAQ.... Say I
have a program "myprog" which generates lots of output, and thus might
frequently be run via
% myprog > logfile
% myprog > logfile 2>&1
Assume myprog is a wrapper which mostly execs other programs (for
instance a compiler driver that runs front end, back end, assembler,
linker, ...). Now what if myprog wants to inspect some of the output
which it (or more likely one of its children) wrote to the logfile?
Obviously, if the output didn't go to a seekable device you're SOL.
But if it went to a regular file it should in theory be possible to
rewind and read it. The first problem is that myprog doesn't know the
name of the logfile since it was opened by the parent shell which simply
handed an open file descriptor to myprog. But that's no problem; we have
the file descriptor and can see if it's rewindable. Now we get to the
next problem: according to truss, most shells do redirection by passing
the O_WRONLY (as opposed to O_RDWR) flag to open(). So, though we have
the file descriptor we're not allowed to read from it. A little test
program confirms this. I took a look at fdopen() but that states clearly
that the new fd cannot have rights the original didn't have (naturally).
Which leads to a couple of questions:
(1) Does anyone know of a workaround? A clever way to (a) determine if
your output went to a disk file and (b) rewind and read back that output
if so? No need to mention the obvious way (passing in the name of the
file on the command line and letting myprog open it).
(2) Is there a good reason for shells to prevent you from reading the
output you just wrote? I can't see a security issue here and am
wondering if it's just historical. Of course I realize that existing
shells won't be changed in our lifetimes even it made sense to do so;
just wondering if there's a theoretical reason not to.
||1/7/2004 1:11:23 AM