4

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?

  • Which Unix variant or variants? Does it have a /proc file system? (Mac OS X doesn't; Linux and Solaris do.) Do you need to work on multiple platforms? – Jonathan Leffler Aug 17 '16 at 22:20
  • Including or not stdin, stdout, stderr? – fduff Aug 19 '16 at 12:15
4

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.

| improve this answer | |
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.

| improve this answer | |
  • 1
    In reverse order then use sort -nr – fduff Aug 19 '16 at 12:14
  • @fduff indeed, the OP asked for a descending order. Thanks. – jlliagre Aug 19 '16 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy