這兩年來RAM比較貴,程式卻是新版比舊版更肥大,如你的電腦又舊了一點,裝的RAM不太夠多,結果有一天你在做某件事、用某個程式、執行某個動作時,不明原因整個系統鎖死。反向推論,應該是執行的程式把目前free的RAM吃光了!
等到發現不對勁時,趕緊按Ctrt+Atl+F1,想切換到console模式手動砍掉某個程式,阻止事態擴大引發大爆炸,但這時候應該是按什麼鍵都沒任何反應,因為RAM已經耗盡,沒辦法執行你的操作,最後只有重新開機,沒存檔的東西全都蒸發了。
當然平常可以使用free指令去檢查當下RAM/swap的使用狀態,但這是不夠的,因為事情發生都是在檢查過後的不知道什麼時候炸開。因此最好是安裝類似近迫武器系統的systemd-oomd或earlyoom來避免發生RAM耗盡的情況發生。當近迫系統發現能用的RAM少於整體RAM某個比例時,就會啟動方陣快炮,把正在吃RAM的程式打掉,維持系統正常運作。
這裡介紹兩個吃RAM少、吃CPU也少的防衛系統。
systemd-oomd:
userspace out-of-memory (OOM) killer systemd-oomd is a system service that uses cgroups-v2 and pressure stall information (PSI) to monitor and take action on processes before an OOM occurs in kernel space.
使用RAM介於2至5MB,耗用CPU接近於 0%(由Kernel Pressure Stall Information來觸發)
earlyoom:
Earlyoom is an userspace OOM-killer which can avoid the system to get into unresponsive state caused by swapping, which is most likely to occur when a large swap is present and memory is tight. It checks the amount of available memory and swap periodically, and when both are below a preconfigured value, it kills the largest process.
使用RAM低於2MB,耗用CPU接近 0.1%(default每秒偵測10次)
以上兩者在多數Linux系統的repository裡面都有,只要用系統的軟體管理程式像是apt, dnf, pacman就能簡單安裝,不過根據earlyoom作者在 https://github.com/rfjakob/earlyoom 裡的說明提到 "earlyoom wants to be simple and solid. It is written in pure C with no dependencies." 看起來比 systemd-oomd簡捷,也可以直接抓github裡的source回來make、安裝,很簡單。
安裝好某一個預警裝置後,可以用"tail /dev/zero" 來充當吃RAM的怪獸,測試一下預警系統是不是真的能發揮功能?
當然,要先把該存的檔案都存好,以免測試時預警系統沒發生作用的話,通通蒸發光了。