Linux 會把讀取過的檔案內容留在 page cache 中,這讓重複讀取快得驚人,但也可能造成「記憶體好像被吃光」的錯覺。要確認某個檔案到底有沒有被快取、快取了多少,linux-fincore 是最直接的工具。
/usr/bin/linux-fincore --pages=false --summarize --only-cached *
也可以只查單一檔案:
linux-fincore -o /usr/lib64/libz.so.1.2.7
不確定參數就用 --help 查。
--pages=false:不印出逐頁資訊--summarize:比對多個檔案時,輸出彙總報告--only-cached:只列出確實存在 cache 中的檔案統計要特別注意它的限制:只能查指定檔案是否被快取,無法直接指定目錄,所以才需要搭配 shell 的 * 展開來批次處理。
套件名為 linux-ftools,有兩條路可走:
1. RPM 安裝——可到 rpmfind 搜尋對應發行版的套件:
https://www.rpmfind.net/linux/rpm2html/search.php?query=linux-ftools
2. 原始碼編譯——流程就是標準的 autoconf 三步驟:
./configure make make install
其 INSTALL 文件要點整理如下:
configure 會自動偵測系統環境,在各目錄產生 Makefile,並建立 config.status 與 config.log(後者可用於除錯)。./configure CC=c99 CFLAGS=-g LIBS=-lposix。make distclean。/usr/local,可用 --prefix=PREFIX 或 --exec-prefix=PREFIX 更改。make check 可跑自測;make clean 清除編譯產物;make distclean 連 configure 產生的檔案一起清掉。--help、--version、--cache-file=FILE(-C)、--quiet(-q)、--srcdir=DIR。先認識兩個指令組合:
ps -e -o pid,rss
-e(等同 -A)顯示所有程序,-o 指定輸出格式。加上排序:
ps -e -o pid,rss | sed -n '2,$p' | sort -nk2 -r
-r 為反向排序,因此這行會把 rss 由大到小排列。
以下腳本會取出記憶體占用前 50 名的程序,把它們開啟的檔案丟給 linux-fincore 統計(需先安裝 linux-fincore):
#!/bin/bash
# Author: Shanker
# Time: 2016/06/08
if [ ! -f /usr/bin/linux-fincore ]
then
echo "You haven't installed linux-fincore yet"
exit
fi
# 找出 rss 前 50 名的程序
ps -e -o pid,rss | sed -n '2,$p' | sort -nk2 -r | head -50 | awk '{print $1}' > /tmp/cache.pids
if [ -f /tmp/cache.files ]
then
echo "the cache.files is exist, removing now"
rm -f /tmp/cache.files
fi
# 取出這些程序開啟的檔案清單
while read line
do
lsof -p $line 2>/dev/null | awk '{print $9}' >> /tmp/cache.files
done < /tmp/cache.pids
if [ -f /tmp/cache.fincore ]
then
echo "the cache.fincore is exist, removing now"
rm -f /tmp/cache.fincore
fi
# 過濾出真正存在的檔案
for i in `cat /tmp/cache.files`
do
if [ -f $i ]
then
echo $i >> /tmp/cache.fincore
fi
done
/usr/bin/linux-fincore -s `cat /tmp/cache.fincore`
rm -f /tmp/cache.{pids,files,fincore}
解讀結果時記得:page cache 佔用記憶體並不代表浪費。當應用程式需要記憶體時,核心會自動回收這些頁面,因此「可用記憶體」應該看 free -m 中的 available/buffers+cached 欄位,而不是只看 free 那一欄。