Linux – What happens when I close() a file descriptor

file-descriptorslinuxopen files

I am trying to get the whole picture with file descriptors. Say I have process1 which initially has these file descriptors:

 _process1_
|          |
| 0 stdin  |
| 1 stdout |
| 2 stderr |
|__________|

Then I close file descriptor 1:

close(1);

The file descriptor 1 translates(points) to the stdout FILE structure in the kernel's Open Files Table.

With the code above the file descriptor 1 gets deleted from the process's table which becomes:

 _process1_
|          |
| 0 stdin  |
| 2 stderr |
|__________|

But what happens in the kernel? Does the stdout FILE structure get deallocated? How is that possible if stdout is a special file (the monitor) and probably being used by other processes? What about FILE structures that are just normal files (.txt for example)? What if such a file is being used by an other process?

Best Answer

The file descriptor 1 translates to the stdout FILE structure in the Kernel's Open Files Table.

This is a misunderstanding. The kernel's file table has nothing whatsoever to do with user-space file structures.

In any event, the kernel has two levels of indirection. There is the internal structure that represents the file itself, which is reference counted. There is an "open file description" that is reference counted. And then there is the file handle, which is not reference counted. The file structure points the way to the inode itself. The open file description contains things like the open mode and file pointer.

When you call close, you always close the file handle. When a file handle is closed, the reference count on its open file description is decremented. If it goes to zero, the open file description is also released and the reference count on the file itself is decremented. Only if that goes to zero is the kernel's file structure freed.

There is no chance for one process to release a resource another process is using because shared resources are reference counted.

Related Question