Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 清理 swap/buffer/cache:安全釋放記憶體完整指南

編輯:關於 Linux

記憶體壓力大時,手動清理 swap、page cache、dentry/inode cache 可緩解短期瓶頸。本文提供安全命令與前提條件。

1. Swap 清理(慎用)

swapoff -a && swapon -a

前提:可用實體記憶體 > 目前 swap 使用量,否則會觸發 OOM Killer 導致進程被殺。執行前務必確認 free -h。

2. Cache 清理(較安全)

先同步磁碟再丟棄:

sync; sync; sync
echo 3 > /proc/sys/vm/drop_caches
sleep 2
echo 0 > /proc/sys/vm/drop_caches  # 恢復預設行為

分級清理選項

值清理內容適用場景
1Page cache (檔案內容快取)釋放檔案讀取快取
2Dentry + Inode cache (目錄項/索引節點)大量檔案操作後
3全部 (1+2)綜合釋放

/proc/sys/vm/drop_caches 預設值為 0(不自動丟棄)。

自動化與監控建議

  • 不要在 crontab 盲目定時清理,會抵銷快取效益,降低效能
  • 僅在記憶體不足告警、部署前預熱、基準測試前手動執行
  • 長期 swap 高佔用應排查記憶體洩漏或擴充實體記憶體,而非依賴清理
  • 監控指標: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 記憶體管理機制(快取即空閒、自動回收),避免過度干預導致效能下降。

Copyright © Windows教程網 All Rights Reserved