macOS 解決 too many open files

報錯 too many open files 大致有以下三種可能 [1] [2] [3]

  1. 操作系統打開的文件句柄數過多(內核的限制)
  2. launchd 對進程進行了限制
  3. shell 對進程進行了限制

內核的限制

整個操作系統可以打開的文件數受內核參數影響,可以通過以下命令查看

$ sysctl kern.maxfiles
$ sysctl kern.maxfilesperproc

在我電腦上輸出如下

kern.maxfiles: 49152
kern.maxfilesperproc: 42576

好像已經很大了。

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

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

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

kern.maxfiles=20480
kern.maxfilesperproc=18000

這個文件可能需要自行創建

launchd 對進程的限制

獲取當前的限制:

$ launchctl limit maxfiles

輸出類似這樣:

    maxfiles    256            unlimited

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

臨時修改:

$ sudo launchctl limit maxfiles 65536 200000

系統範圍內修改則需要在文件夾 /Library/LaunchDaemons 下創建一個 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>

修改文件權限

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

載入新設定

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

shell 的限制

通過下述命令查看現有限制

$ ulimit -a

得到如下輸出

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

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

總結

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

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

參考

[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

作者: 孑枵

原文鏈接:macOS 解決 too many open files

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://blog.abreto.net/archives/2020/02/macos-too-many-open-files.html