linux - 计算每个进程打开的文件

标签 linux bash ps

我正在开发一个监视进程资源并在 Linux 中定期报告的应用程序,但我在提取每个进程的打开文件数时遇到了问题。

如果我取出所有文件并根据它们的 PID 对它们进行分组并计数,这需要相当长的时间。

如何计算 Linux 中每个进程的打开文件数?

最佳答案

看看 /proc/ 文件系统:

ls /proc/$pid/fd/ | wc -l

要对所有进程执行此操作,请使用:

cd /proc
for pid in [0-9]*
do
    echo "PID = $pid with $(ls /proc/$pid/fd/ | wc -l) file descriptors"
done

作为单行(通过附加 | grep -v "0 FDs" 进行过滤):

for pid in /proc/[0-9]*; do printf "PID %6d has %4d FDs\n" $(basename $pid) $(ls $pid/fd | wc -l); done

作为一个包含命令名称的单行符,按文件描述符计数降序排序(通过附加|head -10限制结果):

for pid in /proc/[0-9]*; do p=$(basename $pid); printf "%4d FDs for PID %6d; command=%s\n" $(ls $pid/fd | wc -l) $p "$(ps -p $p -o comm=)"; done | sort -nr

此附录感谢@Boban:

You can pipe the output of the script above into the following script to see the ten processes (and their names) which have the most file descriptors open:

  ...
done | sort -rn -k5 | head | while read -r _ _ pid _ fdcount _
do
  command=$(ps -o cmd -p "$pid" -hc)
  printf "pid = %5d with %4d fds: %s\n" "$pid" "$fdcount" "$command"
done

这里有另一种方法列出开放fds最多的前十进程,可能可读性较差,所以我不放在前面:

find /proc -maxdepth 1 -type d -name '[0-9]*' \
     -exec bash -c "ls {}/fd/ | wc -l | tr '\n' ' '" \; \
     -printf "fds (PID = %P), command: " \
     -exec bash -c "tr '\0' ' ' < {}/cmdline" \; \
     -exec echo \; | sort -rn | head

关于linux - 计算每个进程打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21752067/

相关文章:

linux - 查找路径不包含单词的文件

linux - 如何找到最后一个spwan线程或进程?

bash - 如何使用 'kill' 结合 'grep' 终止进程

linux 蓝牙 c 语言编程

c - 用C语言读写二进制文件?

linux - Armv8 架构的 Buildroot 配置选项

java版本无法识别

bash - 成功启动systemd后执行bash脚本?

bash - 在 shell 中打印具有多行值的变量?

linux - Bash,显示特定文件夹中的进程