在 CentOS 系統中,ulimit
命令用于設置或控制 shell 進程及其子進程可以使用的系統資源。通過 ulimit
,你可以限制諸如打開的文件數、進程數、CPU 時間等資源。以下是如何使用 ulimit
來限制進程資源的詳細說明和示例。
ulimit
參數-n
:設置單個進程可以打開的最大文件描述符數量。-u
:設置用戶可以同時運行的最大進程數。-t
:設置進程可以使用的最大 CPU 時間(以秒為單位)。-m
:設置進程可以使用的最大內存大?。ㄒ?KB 為單位)。-v
:設置進程可以使用的虛擬內存總量(以 KB 為單位)。-l
:設置進程可以鎖定的最大內存量(以 KB 為單位)。-f
:設置進程可以創建的最大文件大?。ㄒ詨K為單位)。你可以在當前 shell 會話中臨時設置資源限制。例如:
限制打開的文件數為 2048
ulimit -n 2048
限制用戶可以同時運行的進程數為 512
ulimit -u 512
限制進程的 CPU 時間為 3600 秒(1 小時)
ulimit -t 3600
這些設置在關閉當前 shell 會話后將失效。
要使資源限制在系統重啟后依然有效,需要修改系統的配置文件。通常涉及以下兩個文件:
/etc/security/limits.conf
/etc/profile
或用戶的 ~/.bashrc
、~/.bash_profile
/etc/security/limits.conf
編輯 /etc/security/limits.conf
文件,添加如下行來設置用戶或組的資源限制:
# 限制用戶名為 your_username 的用戶的資源
your_username soft nofile 2048
your_username hard nofile 4096
# 限制特定組的資源
@groupname soft nproc 512
@groupname hard nproc 1024
說明:
soft
表示軟限制。hard
表示硬限制。nofile
表示打開文件數的限制。nproc
表示允許的最大進程數。為了讓每個用戶在登錄時自動應用資源限制,可以在 /etc/profile
或用戶的個人啟動文件(如 ~/.bashrc
、~/.bash_profile
)中添加 ulimit
命令。
例如,在 ~/.bashrc
中添加:
# 設置打開文件數
ulimit -n 2048
# 設置最大進程數
ulimit -u 512
注意:
source ~/.bashrc
使更改生效。使用 ulimit -a
命令可以查看當前 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) 123456
max locked memory (kbytes, -l) 64000
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) 512
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
假設你想限制用戶 john
的進程能夠打開的最大文件數為 4096,并且最大進程數為 1024,可以按照以下步驟操作:
編輯 /etc/security/limits.conf
sudo vi /etc/security/limits.conf
添加以下內容:
john soft nofile 4096
john hard nofile 8192
john soft nproc 1024
john hard nproc 2048
修改 ~/.bashrc
以應用限制
vi ~/.bashrc
添加:
ulimit -n 4096
ulimit -u 1024
重新登錄用戶 john
讓更改生效,需要重新登錄用戶 john
,或者執行:
source ~/.bashrc
驗證限制
切換到用戶 john
并運行:
ulimit -a
確認 open files
和 max user processes
已正確設置。
/etc/security/limits.conf
需要超級用戶權限。ulimit
可能不會影響這些服務。需要根據具體情況調整服務的配置文件(如 systemd 服務單元文件)。ulimit
的支持略有不同,確保在目標用戶的 shell 中進行配置。通過合理使用 ulimit
,可以有效地管理系統資源,防止某個進程消耗過多資源,從而提高系統的穩定性和安全性。