Fun with file descriptors
Posted Jun 11, 2007 10:32 UTC (Mon) by
RobSeace (subscriber, #4435)
In reply to:
Fun with file descriptors by nlucas
Parent article:
Fun with file descriptors
No, the only thing guaranteed is that any particular call that creates a new FD will return the lowest numbered FD currently available... That's it... It doesn't guarantee that nothing else outside the app code will use up any FDs... And, no sane code would EVER make such a brain-dead assumption... Because, any programmer worth a damn KNOWS for a fact that LOTS of library code DOES indeed open up lots of FDs of its own for various uses... So, unless you have complete control over the code, and aren't making any library function calls, you better make NO assumptions over what particular FD number you are going to get assigned at any particular time... You can be guaranteed it's the lowest currently available number, but that doesn't mean a whole lot if you don't know all of the currently open FDs...
For instance, this common behavior is fairly reasonable:
close (0);
open ("/dev/null", O_RDONLY);
Assuming that the open() will get FD# 0... That's reasonable enough, because it's hard to imagine the need for either close() or open() to create a persistent extra FD of its own for some use behind your back, and this sort of behavior has historically always worked... But, if you add any other lib function calls between the close() and the open(), you're just asking for trouble, and you can't be too surprised when it doesn't work anymore... (Plus, if you really wanted to write good code, you'd instead use dup2() or freopen() or something, to guarantee assignment of the desired FD#...)
(
Log in to post comments)