1. 程式人生 > >linux ulimit 調優

linux ulimit 調優

程序 all 參數 resource light set per sources 服務器

概要:
linux系統默認open files數目為1024, 有時應用程序會報Too many open files的錯誤,是因為open files 數目不夠。這就需要修改ulimit和file-max。特別是提供大量靜態文件訪問的web服務器,緩存服務器(如squid), 更要註意這個問題。
網上的教程,都只是簡單說明要如何設置ulimit和file-max, 但這兩者之間的關系差別,並沒有仔細說明。

說明:
1. file-max的含義。man proc,可得到file-max的描述:
/proc/sys/fs/file-max
This file defines a system-wide limit on the number of open files for all processes. (See

also setrlimit(2), which can be used by a process to set the per-process limit,
RLIMIT_NOFILE, on the number of files it may open.) If you get lots of error messages
about running out of file handles, try increasing this value:
即file-max是設置 系統所有進程一共可以打開的文件數量 。同時一些程序可以通過setrlimit調用,設置每個進程的限制。如果得到大量使用完文件句柄的錯誤信息,是應該增加這個值。
也就是說,這項參數是系統級別的。

2. ulimit
Provides control over the resources available to the shell and to processes started by it, on systems that allow such control.
即設置當前shell以及由它啟動的進程的資源限制。
顯然,對服務器來說,file-max, ulimit都需要設置,否則就可能出現文件描述符用盡的問題

修改:
1.修改file-max

# echo  6553560 > /proc/sys/fs/file-max  //sysctl -w "fs.file-max=34166",前面2種重啟機器後會恢復為默認值

# vim /etc/sysctl.conf, 加入以下內容,重啟生效
fs.file-max = 6553560


2.修改ulimit的open file,系統默認的ulimit對文件打開數量的限制是1024

# ulimit -HSn 102400  //這只是在當前終端有效,退出之後,open files又變為默認值。當然也可以寫到/etc/profile中,因為每次登錄終端時,都會自動執行/etc/profile

# vim /etc/security/limits.conf  //加入以下配置,重啟即可生效
* soft nofile 65535 
* hard nofile 65535


附錄:
附錄1.
為了讓一個程序的open files數目擴大,可以在啟動腳本前面加上ulimit -HSn 102400命令。但當程序是一個daemon時,可能這種方法無效,因為沒有終端。

附錄2.
如果某項服務已經啟動,再動態調整ulimit是無效的,特別是涉及到線上業務就更麻煩了。
這時,可以考慮通過修改/proc/’程序pid’/limits來實現動態修改!!!

linux ulimit 調優