Reputation: 99606
From APUE
Each standard I/O stream (i.e. each
FILE
object) has an associated file descriptor.
In a program, can multiple FILE
objects share the same file descriptor?
If yes, is it done by calling fdopen()
multiple times with the same given file descriptor, each of which returns a pointer to a different FILE
object?
If I flcose()
on a pointer to a given FILE
object, will the file descriptor of the FILE
object still exists and connects to the file, if there is another FILE
object sharing the same file descriptor?
Thanks.
Upvotes: 2
Views: 1230
Reputation: 215617
Yes, but it's a very bad idea, since fclose
closes the associated fd, and therefore yyou can only fclose
one of them without it resulting in close
on a file descriptor that no longer belongs to the FILE
, and may have been reassigned for other use. In principle this happens even at process termination, unless you use _exit
/_Exit
or abnormal termination.
A related question is whether you can use different file descriptors (each produced by dup
for the same underlying open file description with more than one file. For that, the answer is also yes, and while it may be a bad idea, there are rules POSIX specifies that make it safe if you follow them:
2.5.1 Interaction of File Descriptors and Standard I/O Streams
Upvotes: 3