記憶體壓力大時,手動清理 swap、page cache、dentry/inode cache 可緩解短期瓶頸。本文提供安全命令與前提條件。
swapoff -a && swapon -a
前提:可用實體記憶體 > 目前 swap 使用量,否則會觸發 OOM Killer 導致進程被殺。執行前務必確認 free -h。
先同步磁碟再丟棄:
sync; sync; sync
echo 3 > /proc/sys/vm/drop_caches
sleep 2
echo 0 > /proc/sys/vm/drop_caches # 恢復預設行為
| 值 | 清理內容 | 適用場景 |
|---|---|---|
| 1 | Page cache (檔案內容快取) | 釋放檔案讀取快取 |
| 2 | Dentry + Inode cache (目錄項/索引節點) | 大量檔案操作後 |
| 3 | 全部 (1+2) | 綜合釋放 |
/proc/sys/vm/drop_caches 預設值為 0(不自動丟棄)。
vm.swappiness (預設 60,降低可減少 swap 傾向)、vm.vfs_cache_pressure (預設 100,調高加速 inode 回收)free -h # 觀察 available/buffers/cached 變化
cat /proc/meminfo | grep -E 'Swap|Cached|Buffers|SReclaimable'
理解 Linux 記憶體管理機制(快取即空閒、自動回收),避免過度干預導致效能下降。