0

I am reading Linux System Programming by Robert Love and trying to understand the concept of file descriptors.

He mentions that

File descriptors start at 0 and go up to one less than this maximum value. By default, the maximum is 1,024

So, for example, I have two files open using the file descriptors 500 and 501 respectively.

Now if the file with file descriptor 500 is closed does that mean that the next fd to be allocated will be 502? Can it reuse 500? If so how can it do that, does the kernel maintain all closed file descriptors?

2 Answers 2

2

Linux as with any Unix-like system uses a file distributor table that is maintained by the kernel. open creates a descriptor reusing the lowest closed file descriptor or creates a new entry. close sets that entry closed in the table.

2

The Linux man page for open(2) states that

The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

So if you have only 500 and 501 open, the next one you get is 0. Usually, you'd of course have 0 (stdin), 1 (stdout), and 2 (stderr) pointing to something sensible, or /dev/null if you're a daemon.

8
  • No, but how does the system know the next one is 0. That was my question. Does it keep a pool of all file descriptors that it can now give?
    – ng.newbie
    Jan 3, 2018 at 9:54
  • 1
    @ng.newbie This differs per OS, but generally the system will have a list of all currently allocated file descriptors, so it will just iterate through the file descriptors for a process until it finds an empty one.
    – Hex
    Jan 3, 2018 at 9:57
  • @KingGraham "Iterate through all file descriptors" Isn't that really inefficient?
    – ng.newbie
    Jan 3, 2018 at 9:59
  • @ng.newbie Think of file descriptors as an index into a (pre-allocated) array of file information. Iterating over an array is fast, especially compared to the much slower step of actually accessing the file on the filesystem. And if performance really is an issue here the kernel can also keep note of the lowest available slot.
    – nohillside
    Jan 3, 2018 at 10:01
  • @ng.newbie, are wondering how it works conceptually, or about the actual implementation? i.e. do I have to go and check the source code on how the file descriptor table is implemented? :)
    – ilkkachu
    Jan 3, 2018 at 10:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .