6

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
Saulo Silva
  • 163
  • 6

1 Answers1

8

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).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • @zevzek, threads / lwps / tasks depending on how they're called can have different fd / mappings, etc on some systems, even Linux. – Stéphane Chazelas Oct 08 '21 at 21:29
  • @zevzek, it doesn't need to care. On Linux, it can get the info from /proc/pid/task/fd/* – Stéphane Chazelas Oct 08 '21 at 21:42
  • @zevzek, probably not, [you couldn't even tell if two fds from the same process share the same open file description in Linux before 3.5](/q/191967). In any case, I agree that that command in itself is not particularly useful other than to show how to get the same numbers as when you use `lsof` without options like this question is asking. It's still useful to be able to tell what file a thread is using. – Stéphane Chazelas Oct 08 '21 at 21:54