0

I know that I should close opened files. I know that if I don't do that the file descriptors will leak. I also know that file descriptor is just an integer. With that integer os associates some resources. And here is the question. What are those resources? What makes it difficult to create infinite (a lot) file descriptors? Why can't os detect those leakages? And why os doesn't give the same file descriptors for the same file opening?

Zhambul
  • 942
  • 9
  • 23
  • Possible duplicate of [What are file descriptors, explained in simple terms?](http://stackoverflow.com/questions/5256599/what-are-file-descriptors-explained-in-simple-terms) – codeforester Mar 23 '17 at 15:03

1 Answers1

2

What are those resources?

This link posted by codeforester contains some material about.

Anyway, those file descriptors are simply handles to complex data the kernel holds for a program. They could be opaque pointers, but using simple numbers has its advantages (stdin, stdout, stderr have a well-known number, for example). What kind and amount of data is a kernel thing, and a program should not, and doesn't need, to know. So, nor you and me. But, just to speak, for example some buffer is needed. Then, the kernel must know in any moment which files are opened, otherwise, for example, you could unmount a filesystem with open files and leave programs dangling.

What makes it difficult to create infinite (a lot) file descriptors?

Because file descriptors cost ram (and CPU also), which is a finite resource, and nobody wants a kernel crash because some (stupid) programmer wastes file descriptors... :-). So, the kernel reserves a finite amount of resources for file descriptors (which are not always simple files). Kernels are not all equal, each can have its policy and often some way for users to manage relevant settings.

Why can't os detect those leakages?

Because it can not. The kernel can not tell the difference between a poor written program, which leaks resources, and a program which legitimately allocates many resources. Moreover, it is not the duty of a kernel to try to distinguish good programs from bad ones. A kernel must supply services, fast and efficiently -- all the rest is responsibility of programmers.

And why os doesn't give the same file descriptors for the same file opening?

Because it is legitimate to open the same file twice or more. Two programs can open the same file, two threads can, or even a single thread. And the kernel must always respect the "contract" its API claims, always in the same manner: again, it is the programmer who must know what he is doing.

Community
  • 1
  • 1