當程式開啟的檔案或 socket 連線數量超過系統設定上限時,就會看到 too many open files 這類錯誤訊息。以下整理排查與調整方式。
ulimit -a
輸出範例:
fdipzone@ubuntu:~$ ulimit -a core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 20 file size (blocks, -f) unlimited pending signals (-i) 16382 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) unlimited virtual memory (kbytes, -v) unlimited file locks (-x) unlimited
其中 open files (-n) 1024 代表每個用戶最多可開啟 1024 個檔案。
lsof | wc -l watch "lsof | wc -l"
lsof -p 1234 | wc -l
ulimit -n 2048
調整後再用 ulimit -a 確認,會看到 open files 已變成 2048。這種方式只在當前 shell 有效,重新登入或重開機就會回到預設值。
編輯 /etc/security/limits.conf,在檔案結尾加入:
vim /etc/security/limits.conf * soft nofile 4096 * hard nofile 4096
最前面的 * 代表所有用戶;若只想針對單一帳號設定,可改成:
fdipzone soft nofile 8192 fdipzone hard nofile 8192
存檔後登出再重新登入即可生效。
實務上建議先釐清是真的需要更多 fd,還是程式有檔案描述符未釋放的問題,否則單純把上限調高只是延後故障發生。