ulimit 是 shell 的內建指令,用來控制 shell 所執行程序的資源上限。
ulimit -a:
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 8064
max locked memory (kbytes, -l) 32
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) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 8064
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
對需要大量 socket 連線並維持長時間開啟的 Java 應用而言,預設的 1024 個檔案描述符很容易就爆,常見錯誤是「Socket/File: Can't open so many files」或「too many open files」。用 ulimit -n xx 提高每個程序可開啟的檔案數即可。
在 /etc/rc.local 中增加:ulimit -SHn 65535
在 /etc/profile 中增加:ulimit -SHb 65535,然後 source /etc/profile 讓參數即時生效。
在 /etc/security/limits.conf 中增加:
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
* 代表所有使用者,nproc 是最大程序數,nofile 是最大檔案開啟數。改完要生效,關掉目前 session 重新連線即可。
很多人寫得含糊:這個 1024 到底是系統限制還是使用者限制?答案是使用者限制——更精確地說,是「當前使用者接下來要執行的程序」的限制。因此:
1. 它是針對單一程序的限制。
2. 不會改變之前已經在跑的程序。
3. 用 ulimit 指令改的值,退出 shell 就消失。
例如先跑程式 A,再用 ulimit 把限制改成 2048 然後跑 B,退出 shell 重新登入後跑 C,那麼只有 B 能開 2048 個句柄。
把 ulimit 指令塞進 /etc/profile 是常見但並不理想的做法;正確作法是改 /etc/security/limits.conf。
那系統總限制呢?在 /proc/sys/fs/file-max,可以用 cat 查看目前值,用 echo 立即修改。另外 /proc/sys/fs/file-nr 是唯讀的,能看到整個系統目前使用的檔案句柄數量。
排查句柄問題時,lsof 非常實用:能看某個程序開了哪些句柄,也能看某個檔案或目錄被誰佔用。
若使用 squid,要在 /etc/init.d/squid 裡加 ulimit -HSn 65535,並在 squid.conf 中設 max_filedesc 16384。
最後提醒:上面這種方式只改變使用者登入後的檔案開啟數,對 /etc/init.d/nginx、php 這類啟動腳本並不生效。這類腳本必須在腳本內部自己加一行 ulimit -HSn 65535 才行。