LOST in a PIPE

Tom Christiansen tchrist at convex.COM
Tue Feb 26 05:30:38 AEST 1991


>From the keyboard of jik at athena.mit.edu (Jonathan I. Kamens):
:
:  Well, you can't use system() or popen(), because neither of them allow you
:to do what you want to to, i.e. read the stderr output of the tar process.  In
:the former case, system(), it doesn't allow you to read any output at all.  In
:the latter case, popen(), you can read stdout but not stderr, since stderr
:automatically goes to whatever the stderr of your process is.

This isn't strictly true.  Remember that you've got the full power of
sh descriptor manipulation to help you out.  

First of all, you can dup stderr to stdout:

    if (!(fp = popen("cmd 2>&1", "r")))
	perror("couldn't popen of cmd");

Then they are read together as one merged stream.

If you want to read just stderr, not stdout, you can do this:

    fp = popen("3>&1 (cmd 2>&1 1>&3 3>&-) 3>&-", "r");

Now when you do your fgets() or whatever on that fp, you'll be reading his
stderr instead of his stdout.  His old stdout will be left unaffected,
that is, will be your program's stdout.  You can obviously redirect this
easily enough.

Now, if you really want to read both stdout and stderr separately, then
yes, you do have to more complex contortions, preferably involving
select.


--tom
-- 
"UNIX was not designed to stop you from doing stupid things, because
 that would also stop you from doing clever things." -- Doug Gwyn

 Tom Christiansen                tchrist at convex.com      convex!tchrist



More information about the Comp.unix.programmer mailing list