How to list number of open file descriptors by process for all processes on Unix

lsof

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?

Best Answer

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.

Related Question