Linux如何限制流程的資源使用情況
要限制Linux中進程的資源使用,應根據資源類型選擇合適工具:1. 使用ulimit限制單個進程的內存、文件大小、打開文件數和CPU時間,但不支持CPU或I/O帶寬限制;2. 使用cgroups(通過systemd-run或手動操作)實現對CPU、內存和I/O帶寬的精細控制,適用於現代系統並被Docker等容器技術採用;3. 使用nice調整進程CPU調度優先級,降低其在系統繁忙時的資源競爭能力,或使用cpulimit動態暫停進程以限制CPU使用率;4. 使用ionice設置I/O優先級,結合cgroups v2的io.max實現I/O帶寬硬限制;綜上,推薦systemd-run配合cgroups作為最簡潔的資源限制方案,ulimit適用於簡單場景,cpulimit適合快速限制CPU使用,最終選擇取決於系統版本和限制嚴格性需求。
If you need to limit the resource usage (CPU, memory, disk I/O, etc.) of a process in Linux, there are several built-in tools and mechanisms you can use. Here are the most practical and widely supported methods:
1. Using ulimit
to restrict per-process resources
ulimit
is a shell builtin that controls limits on resources for processes started from that shell. It's useful for setting limits like maximum memory, file size, number of open files, and CPU time.
Common usage:
# Limit virtual memory to 500 MB ulimit -v 512000 # Limit CPU time to 60 seconds ulimit -t 60 # Limit max file size to 10 MB ulimit -f 10240 # Limit number of open file descriptors ulimit -n 256
Example:
ulimit -v 512000 ./your_program
⚠️ Note:
ulimit
only affects the current shell and child processes. It doesn't support CPU or I/O bandwidth limiting.
2. Using cgroups
(Control Groups) for fine-grained control
For more advanced and flexible resource limiting (especially CPU and memory), use cgroups . Modern Linux systems use cgroups v2 , often managed via systemd
or directly through the filesystem.
Option A: Using systemd-run
(easiest for one-off processes)
# Limit a process to 50% CPU and 500MB memory systemd-run \ --scope \ --cpu-quota=50000% \ --memory-limit=500M \ ./your_program
-
--cpu-quota=50000%
means 50% of one CPU core (100% = 1 full core, so 50000% = 50%). -
--memory-limit=500M
kills the process if it exceeds 500 MB.
Option B: Manual cgroups v2 (more control)
Create a cgroup:
sudo mkdir /sys/fs/cgroup/limited
Set memory limit:
echo 536870912 | sudo tee /sys/fs/cgroup/limited/memory.max # 512 MB
Set CPU limit (eg, 20% of one core):
echo 20000 | sudo tee /sys/fs/cgroup/limited/cpu.max # Format: "max period" → "20000 100000" means 20% CPU echo "20000 100000" | sudo tee /sys/fs/cgroup/limited/cpu.max
Add a process to the cgroup:
./your_program & echo $! | sudo tee /sys/fs/cgroup/limited/cgroup.procs
This method is powerful and used by container runtimes like Docker.
3. Using nice
and cpulimit
for CPU control
nice
– Adjust process scheduling priority
Doesn't limit CPU usage, but reduces priority so it gets less CPU when the system is busy.
nice -n 19 ./your_program
-
-n 19
is the lowest priority.
cpulimit
– Actively limit CPU percentage
Install (if not available):
sudo apt install cpulimit # Debian/Ubuntu
Limit a running process by name or PID:
cpulimit -l 30 -p $(pgrep your_program)
Or launch a process with limit:
cpulimit -l 30 -- ./your_program
cpulimit
works by pausing the process usingSIGSTOP
/SIGCONT
, so it's not perfectly smooth but effective.
4. Limiting disk I/O with ionice
Use ionice
to control I/O priority (best effort, not hard limits).
# Run with idle I/O priority (only uses disk when idle) ionice -c 3 ./your_program # Or low priority (class 2, level 7) ionice -c 2 -n 7 ./your_program
For hard I/O rate limiting, use cgroups v2
with io.max
(similar to memory/cpu limits).
Example:
# Limit to 10 MB/s read, 5 MB/s write echo "rbytes=10485760 wbytes=5242880" | sudo tee /sys/fs/cgroup/limited/io.max
Summary: Which tool to use?
Resource | Recommended Tool |
---|---|
Memory | systemd-run --memory-limit or cgroups |
CPU | systemd-run --cpu-quota , cgroups , or cpulimit
|
File size / open files | ulimit
|
CPU priority | nice
|
I/O priority | ionice
|
I/O bandwidth | cgroups v2 io.max
|
For most users, systemd-run
with cgroups is the cleanest way to limit CPU and memory. For scripting and simple cases, ulimit
is sufficient. For older systems or quick CPU caps, cpulimit
is handy.
Basically, it depends on your Linux version and how strict the limits need to be.
以上是Linux如何限制流程的資源使用情況的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

在Linux上安裝軟件主要有三種方法:1.使用包管理器,如apt、dnf或pacman,通過更新源後執行install命令安裝,例如sudoaptinstallcurl;2.對於.deb或.rpm文件,分別使用dpkg或rpm命令安裝,並在需要時修復依賴;3.使用snap或flatpak跨平台安裝應用,如sudosnapinstall軟件名,適用於追求版本更新的用戶,推薦優先使用系統自帶包管理器以獲得更好的兼容性和性能。

cronisusedforpreciseschedulingonalways-onsystems,whileanacronensuresperiodictasksrunonsystemsthataren'tcontinuouslypowered,suchaslaptops;1.Usecronforexacttiming(e.g.,3AMdaily)viacrontab-ewithsyntaxMINHOURDOMMONDOWCOMMAND;2.Useanacronfordaily,weekly,o

ChoosePop!_OS,Ubuntu,NobaraLinux,orArchLinuxforoptimalgamingperformancewithminimaloverhead.2.InstallofficialNVIDIAproprietarydriversforNVIDIAGPUs,ensureup-to-dateMesaandkernelversionsforAMDandIntelGPUs.3.EnabletheperformanceCPUgovernor,usealow-latenc

Linux適合老舊硬件、安全性高、可定制,但軟件兼容性弱;Windows軟件豐富、易用,但資源佔用高。 1.性能上,Linux輕量高效,適合舊設備;Windows對硬件要求高。 2.軟件上,Windows兼容性更廣,尤其專業工具和遊戲;Linux需借助工具運行部分軟件。 3.安全上,Linux權限管理更嚴格,更新便捷;Windows雖有防護但仍易受攻擊。 4.使用難度上,Linux學習曲線陡峭;Windows操作直觀。根據需求選擇:重性能與安全選Linux,重兼容與易用選Windows。

timessynchronizationiscroucialforsystemriabilitile andsecurityBecurityBecurityBecurityTimecauseslogConfusion,SecurityFailures,不正確的SCHEDULEDTASKS,and distributedSystementerors; 1.CheckntpStatusptatususistimeDimeDimeDatectlstatectlstatustatustoconFirmSynChronChronChronChronizationServiciative and servicivity; 2

RAIDimprovesstorageperformanceandreliabilityonLinuxserversthroughvariousconfigurations;RAID0offersspeedbutnoredundancy;RAID1providesmirroringforcriticaldatawith50�pacityloss;RAID5supportssingle-drivefailuretoleranceusingparityandrequiresatleastthre

要管理Linux服務的開機啟動,使用systemctl命令即可。 1.檢查服務狀態:systemctlstatus可查看服務是否運行、啟用或禁用。 2.啟用服務開機啟動:sudosystemctlenable,如sudosystemctlenablenginx,若同時啟動則用sudosystemctlenable--nownginx。 3.禁用服務開機啟動:sudosystemctldisable,如sudosystemctldisablecups,若同時停止則用sudosystemctldisabl

InstallPythonandessentialtoolsusingyourdistribution’spackagemanager,ensuringpython3-venvandpython3-devareincludedforenvironmentisolationandCextensions.2.Alwaysusevirtualenvironmentsbyrunningpython3-mvenvmyproject_envandactivatewithsourcemyproject_env
