Discrepancy with lsof command when trying to get the count of open files per process

I am trying to get a list of open files per process. I ran the following one-liner from PerlMonks:

lsof | perl -lane '$x{"$F[0]:$F[1]"}++;
END { print "$x{$_}t$_" for sort {$x{$a}<=>$x{$b}} keys %x}'

It returns the total count of open files, and the process name and pid. The result is sorted in ascending order, and the last line is as follows:

1065702 java:15437

So when I run lsof -p 15437, I would expect it to return the same number, however I’m getting:

$ lsof -p 15437 | wc -l
403

Why the discrepancy?

Addendum

A third source of discrepancy:

$ cd /proc/15437/fd
$ ls -1 | wc -l
216

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

lsof without arguments gives you the information for all the threads of the every process.

While lsof -p "$pid" only lists open files for the process.

To get the same number, you’d need:

lsof -a -K -p "$pid"

Also note that lsof doesn’t only list files open on file descriptors, it also lists mmapped files (as seen in /proc/*/task/*/maps), the current working directory (as seen in /proc/*/task/*/cwd), the root directory (/proc/*/task/*/root).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x