I've noticed, if a file is renamed, lsof displays the new name.

To test it out, created a python script:

import time

f = open('foo.txt', 'w')
while True:

Saw that lsof follows the rename:

$ python test_lsof.py &
[1] 19698

$ lsof | grep foo | awk '{ print $2,$9 }'
19698 /home/bfernandez/foo.txt

$ mv foo{,1}.txt

$ lsof | grep foo | awk '{ print $2,$9 }'
19698 /home/bfernandez/foo1.txt

Figured this may be via the inode number. To test this out, I created a hard link to the file. However, lsof still displays the original name:

$ ln foo1.txt foo1.link

$ stat -c '%n:%i' foo*

$ lsof | grep foo | awk '{ print $2,$9 }'
19698 /home/bfernandez/foo1.txt

And, if I delete the original file, lsof just lists the file as deleted even though there's still an existing hard link to it:

$ rm foo1.txt
rm: remove regular empty file ‘foo1.txt’? y

$ lsof | grep foo | awk '{ print $2,$9,$10 }'
19698 /home/bfernandez/foo1.txt (deleted)

So finally...

My question

What method does lsof use to keep track open file descriptors that allow it to:

  1. Keep track of filename changes
  2. Not be aware of existing hard links
  1. You are right in assuming that lsof uses the inode from the kernel's name cache. Under Linux platforms, the path name is provided by the Linux /proc file system.

  2. The handling of hard links is better explained in the FAQ:

3.3.4 Why doesn't lsof report the "correct" hard linked file path name?

When lsof reports a rightmost path name component for a file with hard links, the component may come from the kernel's name cache. Since the key which connects an open file to the kernel name cache may be the same for each differently named hard link, lsof may report only one name for all open hard-linked files. Sometimes that will be "correct" in the eye of the beholder; sometimes it will not. Remember, the file identification keys significant to the kernel are the device and node numbers, and they're the same for all the hard linked names.

The fact that the deleted node is displayed at all is also specific to Linux (and later builds of Solaris 10, according to the same FAQ).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.