计算每个进程的打开文件 [英] Counting open files per process

查看:80
本文介绍了计算每个进程的打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on an application that monitors the processes' resources and gives a periodic report in Linux, but I faced a problem in extracting the open files count per process.

如果我拿走所有文件并根据其PID将它们分组并计数,这将花费相当长的时间.

This takes quite a while if I take all of the files and group them according to their PID and count them.

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

推荐答案

看看/proc/文件系统:

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

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

To do this for all processes, use this:

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

感谢@Boban的附录:您可以将上述脚本的输出通过管道传递到以下脚本中,以查看打开文件描述符最多的十个进程(及其名称):

Credit to @Boban for this addendum: 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的前十个进程的另一种方法,可能可读性较差,所以我不放在前面:

Here's another approach to list the top-ten processes with the most open fds, probably less readable, so I don't put it in front:

find -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

这篇关于计算每个进程的打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆