Linux 计算每个进程打开的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21752067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting open files per process
提问by Aladdin
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.
我正在开发一个监视进程资源并在 Linux 中提供定期报告的应用程序,但我在提取每个进程的打开文件数时遇到了问题。
This takes quite a while if I take all of the files and group them according to their PID and count them.
如果我获取所有文件并根据它们的 PID 对它们进行分组并对其进行计数,这将花费相当长的时间。
How can I take the open files count for each process in Linux?
如何获取 Linux 中每个进程的打开文件数?
采纳答案by Alfe
Have a look at the /proc/
file system:
查看/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
EDIT: 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:
编辑:感谢@Boban 此附录:您可以将上面脚本的输出通过管道传输到以下脚本中,以查看打开文件描述符最多的十个进程(及其名称):
...
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
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:
这是另一种列出fds打开最多的前十个进程的方法,可能可读性较差,所以我不把它放在前面:
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 'ps aux | sed 1d | awk '{print "fd_count=$(lsof -p " " | wc -l) && echo " " $fd_count"}' | xargs -I {} bash -c {}
' ' ' < {}/cmdline" \; \
-exec echo \; | sort -rn | head
回答by Cokorda Raka
Try this:
尝试这个:
for pid in `ps -o pid -u username` ; do echo "$(ls /proc/$pid/fd/ 2>/dev/null | wc -l ) for PID: $pid" ; done | sort -n | tail
回答by JG_
I used this to find top filehandler-consuming processes for a given user (username) where dont have lsof or root access:
我使用它来查找给定用户(用户名)的顶级文件处理程序消耗进程,其中没有 lsof 或 root 访问权限:
ps -opid= -ax | xargs -L 1 -I{} -- sudo bash -c 'echo -n "{} ";lsof -p {} 2>/dev/null | wc -l' | sort -n -k2
回答by Marinos An
This works for me:
这对我有用:
##代码##It prints numopenfiles
per pid
sorted by numopenfiles
.
它numopenfiles
按pid
排序方式打印numopenfiles
。
It will ask for sudo password once.
它会要求输入 sudo 密码一次。
Note that the sum of the above numbers might be bigger than the total number of open files from all processes.
As I read here: forked processes can share file handles
请注意,上述数字的总和可能大于所有进程打开的文件总数。
正如我在这里读到的:分叉的进程可以共享文件句柄