fileno(stdin) versus STDIN_FILENO and friends

Peter Dufault dufault at hda.com
Wed Mar 16 10:49:12 UTC 2011


On Mar 15, 2011, at 1:14 , Till Straumann wrote:

> In general, FILE objects are 'global', i.e., a FILE opened by one
> thread doesn't go away when the thread is deleted. However,
> unless the patches provided with bugzilla #1247 etc. are applied
> there are race conditions when multiple threads access the same FILE
> (or try to fopen() different files concurrently).
> (Sidenote: other newlib objects are also unprotected unless 1247 is
> fixed).
> 
> HOWEVER: stdin/stdout/stderr are treated differently by newlib.
> These three FILEs are 'per-thread' entities and are destroyed
> (albeit this currently may still leak memory, see PR #1246)
> when a thread is deleted.
> 
> Note that the stdin/stdout/stderr FILEs are 'lazy-initialized'
> upon first use, i.e., a thread which doesn't use them doesn't
> create them.
> 
> -> stdin/stdout/stderr refer to different streams/buffers
>    for each thread (but read/write the same underlying file
>    descriptors) and the buffers are 'attached' to the
>    thread's 'reent' struct.
> -> other FILEs are global and attached to the global 'reent'
>    struct.
> 

I think the non-standard behavior I want is for file descriptors 0, 1, and 2 to be different for each thread and optionally inherited from the creating thread.  I need to think about it some more and maybe try it out, I think it can be rigged up with a task-switch hook using dup2 as long as you're willing to keep a spare open file descriptor around.  You could dup2 it out to descriptor at switch-out time and then back in at switch-in time.

Peter
-----------------
Peter Dufault
HD Associates, Inc.      Software and System Engineering





More information about the users mailing list