too many open files; retrying in 1s

macOS 解決 too many open files

報錯 too many open files 大致有以下三種可能 [1] [2] [3]
1. 操作系統(tǒng)打開的文件句柄數(shù)過多(內(nèi)核的限制)
2. launchd 對進程進行了限制
3. shell 對進程進行了限制

內(nèi)核的限制

整個操作系統(tǒng)可以打開的文件數(shù)受內(nèi)核參數(shù)影響,可以通過以下命令查看

$ sysctl kern.maxfiles
$ sysctl kern.maxfilesperproc

在我電腦上輸出如下

kern.maxfiles: 49152
kern.maxfilesperproc: 42576

好像已經(jīng)很大了。

如果需要臨時修改的話,運行如下命令

$ sudo sysctl -w kern.maxfiles=20480 # 或其他你選擇的數(shù)字
$ sudo sysctl -w kern.maxfilesperproc=18000 # 或其他你選擇的數(shù)字

永久修改,需要在 /etc/sysctl.conf 里加上類似的下述內(nèi)容

kern.maxfiles=20480
kern.maxfilesperproc=18000

這個文件可能需要自行創(chuàng)建

launchd 對進程的限制

獲取當(dāng)前的限制:

$ launchctl limit maxfiles

輸出類似這樣:

    maxfiles    256            unlimited

其中前一個是軟限制,后一個是硬件限制。

臨時修改:

$ sudo launchctl limit maxfiles 65536 200000

系統(tǒng)范圍內(nèi)修改則需要在文件夾 /Library/LaunchDaemons 下創(chuàng)建一個 plist 文件 limit.maxfiles.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>limit.maxfiles</string>
    <key>ProgramArguments</key>
    <array>
      <string>launchctl</string>
      <string>limit</string>
      <string>maxfiles</string>
      <string>65536</string>
      <string>200000</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>ServiceIPC</key>
    <false/>
  </dict>
</plist>

修改文件權(quán)限

$ sudo chown root:wheel /Library/LaunchDaemons/limit.maxfiles.plist
$ sudo chmod 644 /Library/LaunchDaemons/limit.maxfiles.plist

載入新設(shè)定

$ sudo launchctl load -w /Library/LaunchDaemons/limit.maxfiles.plist

shell 的限制

通過下述命令查看現(xiàn)有限制

$ ulimit -a

得到如下輸出

...
-n: file descriptors                256
...

通過 ulimit -S -n 4096 來修改。如果需要保持修改,可以將這一句命令加入你的 .bash_profile.zshrc 等。

總結(jié)

一般來說,修改了上述三個限制,重啟一下,這個問題就可以解決了。

在實際操作中,我修改到第二步重啟,第三個就自動修改了。

參考

[1] https://bbs.huaweicloud.com/blogs/108323
[2] https://www.launchd.info/
[3] https://en.wikipedia.org/wiki/Launchd#launchctl
[4] https://superuser.com/questions/433746/is-there-a-fix-for-the-too-many-open-files-in-system-error-on-os-x-10-7-1
[5] https://wilsonmar.github.io/maximum-limits/
[6] https://superuser.com/questions/302754/increase-the-maximum-number-of-open-file-descriptors-in-snow-leopard
[7] https://krypted.com/mac-os-x/maximum-files-in-mac-os-x/
[8] https://medium.com/mindful-technology/too-many-open-files-limit-ulimit-on-mac-os-x-add0f1bfddde

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容