16

Background: I'm playing around with monitoring the ulimit for running processes for a particular user. (I had occasionally seen processes that were getting started with an incorrect limit.) I asked a couple self-professed Linux gurus, and one suggested lsof -p <pid>, while the other suggested ls /proc/<pid>/fd, but neither was positive about which more accurately reflects the actual count towards the max open files limit for a process.

So, which is it?

lsof -p <pid> | wc -l

Or

ls /proc/<pid>/fd | wc -l

Please elaborate on the difference. Thanks!

Jared
  • 263
  • 2
  • 6
  • 3
    Sounds like homework. – ewwhite Oct 21 '11 at 23:48
  • 1
    Not homework. Added better explanation. I had read the `lsof` man pages, and while I suspected the answer was memory-mapped files, I wanted a more experienced person's confirmation. – Jared Oct 24 '11 at 16:45

1 Answers1

13

lsof will also give you memory mapped .so-files - which technically isn't the same as a file handle the application has control over. /proc/<pid>/fd is the measuring point for open file descriptors - however: Mentioned in the proc-man page - if the main thread of a multithreaded program has terminated, this directory will be unavailable.

lsof -p <pid> | grep -v mem | egrep -v '^COMMAND PID' | wc -l will show you the same items as ls /proc/<pid>/fd | wc -l.

The memory maps is available in /proc/<pid>/maps.

Kvisle
  • 4,113
  • 23
  • 25
  • 1
    The `lsof` gives you almost the same output, but it also includes `cwd`, `rtd` and `txt` file descriptors. – Ian Bamforth Mar 21 '16 at 14:55
  • 1
    Also note that the number of spaces between `COMMAND` and `PID` may vary. Replace the spaces with `[[:space:]]*` to make it more general. – Ian Bamforth Mar 21 '16 at 14:56
  • I also found `lsof -a -p -d ^mem -d ^cwd -d ^rtd -d ^txt -d ^DEL | wc -l` [here](https://access.redhat.com/solutions/1210583), while the `lsof` in Android shell (`adb shell`) doesn't support `-a` and `-d`. So I use Kvisle's version finally. – Weekend Jul 09 '18 at 03:05