unofficial mirror of libc-alpha@sourceware.org
 help / color / mirror / Atom feed
* Resource use fopen-vs-freopen
@ 2022-12-04 21:34 David Seifert via Libc-alpha
  2022-12-05 18:55 ` Zack Weinberg via Libc-alpha
  0 siblings, 1 reply; 2+ messages in thread
From: David Seifert via Libc-alpha @ 2022-12-04 21:34 UTC (permalink / raw)
  To: libc-alpha

Hi glibc,
this came up recently as a point of interest. Say we have snippet 1:

  #include <stdio.h>

  void reset_std_streams(void) {
    stdin = fopen("/dev/null", "r");
  }

  int main(void) {
    reset_std_streams();
    // A
    /*
    -- actual program code --
    */
  }

and snippet 2:

  #include <stdio.h>

  void reset_std_streams(void) {
    freopen("/dev/null", "r", stdin);
  }

  int main(void) {
    reset_std_streams();
    // B
    /*
    -- actual program code --
    */
  }

When comparing the total tally of all resources used at point A in
snippet 1 and point B in snippet 2, is there an actual difference? Are
there any resources in terms of buffers, memory mapped pages or other
static or dynamic resources that freopen() variant would use that the
fopen() variant would not?

^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: Resource use fopen-vs-freopen
  2022-12-04 21:34 Resource use fopen-vs-freopen David Seifert via Libc-alpha
@ 2022-12-05 18:55 ` Zack Weinberg via Libc-alpha
  0 siblings, 0 replies; 2+ messages in thread
From: Zack Weinberg via Libc-alpha @ 2022-12-05 18:55 UTC (permalink / raw)
  To: libc-alpha

On 2022-12-04 4:34 PM, David Seifert via Libc-alpha wrote:
...
>    void reset_std_streams(void) {
>      stdin = fopen("/dev/null", "r");
>    }
...
>    void reset_std_streams(void) {
>      freopen("/dev/null", "r", stdin);
>    }
...

> When comparing the total tally of all resources used at point A in
> snippet 1 and point B in snippet 2, is there an actual difference?

Yes.  Snippet 1 leaks the old FILE object and, critically, *does not 
change file descriptor 0*, which remains open on the old stdin.

zw

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2022-12-05 18:55 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2022-12-04 21:34 Resource use fopen-vs-freopen David Seifert via Libc-alpha
2022-12-05 18:55 ` Zack Weinberg via Libc-alpha

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).