Search code examples
clinuxposix

Count of references to a object referenced by file descriptor


Is it possible to programmatically find out count of processes which have opened object referenced by given file descriptor on linux?

If yes, is there any difference if it is a file, a pipe or whatever?


Solution

  • Curiously, the fuser program and its output has been standardized by POSIX. You could call that using popen and parse its output. Unless the user is privileged, the list will be incomplete, and this approach is inherently prone to races.

    On Linux, you could read the contents of the /proc/*/fd directories and check for referenced to the same file descriptor. (Same comment about privileges and races applies.) If you are interested in references to the same file description object (which share not just the same file, but also the same file offset because they were created by dup/dup2 or fork), you'll have to filter this further using the kcmp system call.