6

I need to list every process and how many file descriptors are open for that process so that I can figure which processes are keeping way too many open files. No, I don't need the number of open files for just one process as other questions have asked. I need to know the number for every running process, preferably sorted in descending order.

lsof doesn't seem like it can do this. Is there any other utility or something that can accomplish this?

2 Answers2

5

I'd do something like:

sudo lsof -FKc |
  awk '
   function process() {
     if (pid || tid) {
       print n, \
             tid ? tid " (thread of " pid ": " pname")" : pid, \
             name
       n = tid = 0
     }
   }
   {value = substr($0, 2)}
   /^p/ {
     process()
     pid = value
     next
   }
   /^K/ {
     tid = value
     next
   }
   /^c/ {
      name = value
      if (!tid)
        pname = value
      next
   }
   /^f/ {n++}
   END {process()}' | sort -rn

For number of open files, and replace /^f/ with /^f[0-9]/ for number of open file descriptors.

2

This will work at least with Solaris and Linux and probably with most other OSes supporting a /proc file system:

#!/bin/sh
cd /proc
echo "  count  pid"
ls -d [1-9]*/fd/* 2>/dev/null | sed 's/\/fd.*$//' | uniq -c | sort -rn

Use -rg instead of -rn under Linux or other OSes using GNU sort.

jlliagre
  • 61,204