Surely if you wanted maximum portability you'd just use the POSIX standard
sysconf(_SC_OPEN_MAX) rather than a non-standard OS specific API, and iterate closing all FDs
& ignoring EBADF for those which aren't open. Obviously not as efficient as closefrom(), but
achieves the same end goal without having to #ifdef for OS specific APIs.
int open_max = sysconf (_SC_OPEN_MAX);
for (int i = 3; i < open_max; i++)
close(i);
In any case, neither this, nor closefrom() really address the use case Uli was targetting. The
core issue is you can't guarrentee that everywhere in your program will take care to close()
FDs between fork & exec. Or the more complex scenario where you /want/ to let certain FDs
propagate to the child - the logic of which FDs to propagate to be kept at the place where the
FD is created - likely a totally different piece of code to that which does the fork/exec. Use
of O_CLOSEXEC gives the maximum flexiblity and control over FD handling
Posted Aug 6, 2008 22:06 UTC (Wed) by quotemstr (subscriber, #45331)
[Link]
the logic of which FDs to propagate to be kept at the place where the
FD is created - likely a totally different piece of code to that which does the fork/exec
The code that calls fork()/exec() ought to be what decides what file descriptors the child inherits. Since that code is also responsible for closing file descriptors, there is no problem.
Conversely, code in some random library should not rely on its open file descriptors being inherited by child processes created by a completely different part of the code. That's spooky action at a distance.
Programs using fork()/exec() should always take care to close unneeded file descriptors. It's good programming. While numerous techniques to do that have been described in this thread, a closefrom() library call would go a long way toward making sure programs actually did what they were supposed to.
Remember: generally, the only way to make people do the Right Thing is to make the Right Thing the Easy Thing.
File descriptor handling changes in 2.6.27
Posted Aug 12, 2008 14:05 UTC (Tue) by endecotp (guest, #36428)
[Link]
Be aware that SC_OPEN_MAX could be a very large number. For example, I've seen the Apache
module portion of the subversion server get very slow because it does this. I would
definitely advocate first trying the /proc/self method, and only falling back to SC_OPEN_MAX
if there's no alternative.