In Mac OS X, how can I get an accurate count of file descriptor usage?

In Mac OS X, how can I get an accurate count of file descriptor usage?

把昨日还给我 发布于 2021-11-25 字数 555 浏览 786 回复 4 原文

On Linux, ulimit -n can be used to change or view the limit on the number of file descriptors for a process, and lsof -p nnn | wc -l seems to consistently report the actual file descriptor usage.

But on Mac OS X, lsof -p nnn | wc -l can return a number higher than the limit. I suppose this means lsof is returning more than just file descriptors, but I can't tell what's what.

Bottom line: How can I get an accurate count of file descriptor usage in Mac OS X?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


妄想挽回 2022-06-07 4 楼

I was looking for which process that had lots of file descriptors - so I guess something like

for pid in `ps aux | tail -n +2 | awk '{print $2}'`; do FCOUNT=`lsof -p $pid | grep -v " txt " | wc -l`; echo "PID: $pid $FCOUNT"; done | sort -nk3
给我一枪 2022-06-07 3 楼

I modified anders' answer, now it only displays the opened fd numbers of a specific process:

FCOUNT=`lsof -p $1 | grep -v " txt " | wc -l`;echo "PID: $1 $FCOUNT" | sort -nk3


$ ./ 5926                                                                                                           
PID: 5926       97
淡墨 2022-06-07 2 楼

lsof can show a lot of things beyond just file descriptors, but most of what is likely inflating your count is the loaded frameworks and libraries for an application. You can look at the "FD" column to see if a line is a file descriptor--in which case it's a number, possibly followed by a letter indicating the mode--or something else (see the description of the FD column in the lsof man page for the full list).

If you just need a rough approximation adding a 'grep -v " txt "' before your wc will get you a lot closer to an accurate value. If you need an exact value, you probably need to put together a regex to feed the output through that filers precisely by the FD column.

双手揣兜 2022-06-07 1 楼

I came across the need for identifying this recently - the command I used to count up the total entries (so more than just file handles, but its relative so therefore relevant imo) is:

lsof | awk '{print $1}' | uniq -c | sort -rn | head

This gives something like the following output (your highest used applications may be different!):

$lsof | awk '{print $1}' | uniq -c | sort -rn | head
2978 Google
 914 Atomx20H
 505 Skype
 476 Microsoft
 375 Screenher
 304 Finder
 292 Dock
 277 Atomx20H
 270 Atomx20H

I usually only need to see the top 10 entries, but you can manipulate head to show as many lines as you like.