file-descriptors – Find Out Which File Descriptors Share the Same Open File Description

file-descriptors

If I do (in a Bourne-like shell):

exec 3> file 4>&3 5> file 6>> file

File descriptors 3 and 4, since 4 was dup()ed from 3, share the same open file description (same properties, same offset within the file…). While file descriptors 5 and 6 of that process are on a different open file description (for instance, they each have their own pointer in the file).

Now, in lsof output, all we see is:

zsh     21519 stephane    3w   REG  254,2        0 10505865 /home/stephane/file
zsh     21519 stephane    4w   REG  254,2        0 10505865 /home/stephane/file
zsh     21519 stephane    5w   REG  254,2        0 10505865 /home/stephane/file
zsh     21519 stephane    6w   REG  254,2        0 10505865 /home/stephane/file

It's a bit better with lsof +fg:

zsh     21519 stephane    3w   REG          W,LG  254,2        0 10505865 /home/stephane/file
zsh     21519 stephane    4w   REG          W,LG  254,2        0 10505865 /home/stephane/file
zsh     21519 stephane    5w   REG          W,LG  254,2        0 10505865 /home/stephane/file
zsh     21519 stephane    6w   REG       W,AP,LG  254,2        0 10505865 /home/stephane/file

(here on Linux 3.16) in that we see fd 6 has different flags, so it has to be a different open file description from the one on fd 3, 4 or 5, but from that we can't tell fd 5 is on a different open file description. With -o, we could also see the offset, but again same offset doesn't guarantee it's the same open file description.

Is there any non-intrusive1 way to find that out? Externally, or for a process' own file descriptors?


1. One heuristic approach could be to change the flags of one fd with fcntl() and see what other file descriptors have their flags updated as a result, but that's obviously not ideal nor fool proof

Best Answer

For Linux 3.5 and onward, this can be accomplished with kcmp(2):

KCMP_FILE

  • Check whether a file descriptor idx1 in the process pid1 refers to the same open file description (see open(2)) as file descriptor idx2 in the process pid2. The existence of two file descriptors that refer to the same open file description can occur as a result of dup(2) (and similar) fork(2), or passing file descriptors via a domain socket (see unix(7)).

The man page provides an example specifically for the use case OP asked. Note that this syscall requires the kernel be compiled with CONFIG_CHECKPOINT_RESTORE set.

Related Question