tags:

views:

135

answers:

2

If 2 file descriptors were dupped to the same file (i.e. 506 and STDOUT), will invoking close(506) cleanup the object associated by both and render STDOUT unusable? Or does kernel implement reference counting for its files?

+7  A: 

The kernel implements reference counting, so the kernel object is not closed until all the file handles pointing to it are closed.

Greg Hewgill
I trust you, i up-voted you. Could you provide a documentation source for posterity? This seems like the type of question that may be visited again.
San Jacinto
@San Jacinto: The reference for `dup(2)` and `close(2)` together imply reference counting; in particular *"If fd is the last copy of a particular file descriptor the resources associated with it are freed"* : http://linux.die.net/man/2/dup http://linux.die.net/man/2/close
Greg Hewgill
Awesome :) Thanks.
San Jacinto
+1  A: 

Reference counters are widely used inside the kernel to avoid race conditions due to the concurrent allocation and releasing of a resource. A reference counter is just an atomic_t counter associated with a specific resource such as a memory page, a module, or a file. The counter is atomically increased when a kernel control path starts using the resource, and it is decreased when a kernel control path finishes using the resource. When the reference counter becomes zero, the resource is not being used, and it can be released if necessary.

You might care to see this if you want to look through this for an overview of Linux Kernel reference counting implementation.

Mustapha Isyaku-Rabiu