Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Q: How to re-open stdout after closing it

713 views
Skip to first unread message

Marco

unread,
Sep 21, 1995, 3:00:00 AM9/21/95
to
I need to re-direct stdout temporarily and then restore it to
its original behavior. The re-directing part is easy with
close(STDOUT_FILENO), dup(fd), and close(fd). I cannot, however,
figure out how to re-open stdout so that output goes where it did
before I did the close(STDOUT_FILENO).

If you could help and it wouldn't be much trouble, would you
please email me with a solution? I'll be glad to summarize to
the net.

Thanks for reading this,

Mark Heroux

mar...@lkg.mts.dec.com

"Steel can be any shape you want if you are skilled enough and
any shape but the one you want if you are not." Robert Pirsig


Kurt Franke

unread,
Sep 22, 1995, 3:00:00 AM9/22/95
to


ofd = fileno(stdout);
sofd = dup(ofd);
nfd = dup2(yourfd, ofd);
/* temporarly using redirected stdout */
nfd = dup2(sofd, ofd);


kf

--

Jeff Dickson

unread,
Sep 27, 1995, 3:00:00 AM9/27/95
to
w...@hadady.com (Wayne M. Hadady) writes:

>In article <43sma6$q...@nntpd.lkg.dec.com> Marco <mar...@lkg.mts.dec.com> writes:
>>I need to re-direct stdout temporarily and then restore it to
>>its original behavior. The re-directing part is easy with
>>close(STDOUT_FILENO), dup(fd), and close(fd). I cannot, however,
>>figure out how to re-open stdout so that output goes where it did
>>before I did the close(STDOUT_FILENO).
>>

>try
> dup2(STDOUT_FILENO, savfd) // save copy of stdout fd
> dup2(tmpfd, STDOUT_FILENO) // attach different open file to stdout
> close(tmpfd)
> write to stdout...
> dup2(savfd, STDOUT_FILENO) // attached saved back to stdout
> close(savfd)

>if you don't gave dup2(3C), the same can be accomplished using dup(2), with
>a bit more work.

You're all aware that dup2() doesn't place the duplicate in the variable
given as its second argument right? More exactly the value of it is used
as an index to the processes descriptor table. If the slot revealed is
already in use the file it refers to is closed just as if close(2v) had
been performed directly. So therefore it is very important that the variable
be initialized beforehand (e.g. savfd = 3; ).

Jeff

Geoff Clare

unread,
Oct 5, 1995, 3:00:00 AM10/5/95
to
In <09-22-1995.466877@wha> w...@hadady.com (Wayne M. Hadady) writes:

>try
> dup2(STDOUT_FILENO, savfd) // save copy of stdout fd

Whoops! You just closed whatever file was attached to savfd. Or if savfd
was uninitialised, dup2() will either fail with EBADF or close a file at
random. To save a copy of the fd, use:

savfd = dup(STDOUT_FILENO);

> dup2(tmpfd, STDOUT_FILENO) // attach different open file to stdout
> close(tmpfd)
> write to stdout...
> dup2(savfd, STDOUT_FILENO) // attached saved back to stdout
> close(savfd)

--
Geoff Clare <g...@root.co.uk>
UniSoft Limited, London, England.

0 new messages