在 Linux 中为特定用户运行的每个进程有多少打开的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18788811/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:50:24  来源:igfitidea点击:

How many open files for each process running for a specific user in Linux

linuxlsof

提问by tesla-rules

Running Apache and Jboss on Linux, sometimes my server halts unexpectedly saying that the problem was Too Many Open Files.

在 Linux 上运行 Apache 和 Jboss,有时我的服务器会意外停止,说问题是打开的文件太多。

I know that we might set a higher limit for nprocand nofileat /etc/security/limits.confto fix the open files problem, but I am trying to get better output, such as using watchto monitor them in real-time.

我知道我们可能会在/etc/security/limits.conf 中nprocnofile设置更高的限制来解决打开文件的问题,但我正在尝试获得更好的输出,例如使用watch实时监控它们。

With this command line I can see how many open files per PID:

通过这个命令行,我可以看到每个 PID 有多少打开的文件:

lsof -u apache | awk '{print }' | sort | uniq -c | sort -n

Output (Column 1 is # of open files for the user apache):

输出(第 1 列是用户 apache 的打开文件数):

1     PID
1335  13880
1389  13897
1392  13882

If I could just add the watch command it would be enough, but the code below isn't working:

如果我可以添加 watch 命令就足够了,但是下面的代码不起作用:

watch lsof -u apache | awk '{print }' | sort | uniq -c | sort -n

回答by Gearoid Murphy

This command will tell you how many files Apache has opened:

此命令将告诉您 Apache 打开了多少个文件:

ps -A x |grep apache | awk '{print }' | xargs -I '{}' ls /proc/{}/fd  | wc -l

You may have to run it as root in order to access the process fd directory. This sounds like you've got a web application which isn't closing its file descriptors. I would focus my efforts on that area.

您可能必须以 root 身份运行它才能访问进程 fd 目录。这听起来像是您有一个未关闭其文件描述符的 Web 应用程序。我会把我的精力集中在那个领域。

回答by reader_1000

You should put the command insides quotes like this:

您应该将命令放在引号中,如下所示:

watch 'lsof -u apache | awk '\''{print }'\'' | sort | uniq -c | sort -n'

or you can put the command into a shell script like test.sh and then use watch.

或者您可以将命令放入像 test.sh 这样的 shell 脚本中,然后使用 watch。

chmod +x test.sh
watch ./test.sh