LINUX檢查一個進程內存增長的腳本
內存泄露很難查。
1、內存有沒有泄露?
2、內存在哪裡泄露?
為了解決第一個問題,吾絞盡腦汁,寫了一個腳本,檢查特定程序的內存增長。即只要增長就會輸出。分享出來供大家參考。
get_pid()
{
process_name=$1
text=`ps -A | grep $process_name`
# 去掉開頭的空格
text=`echo $text | sed -e "s/^[ ]*//g"`
#沒有這個進程
if [ "${text}" = "" ] ; then
pid=0
echo ${pid}
return 0
fi
# 得到進程號之後的空格
pos=`expr index "$text" " "`
pos=`expr $pos - 1`
#截取進程號
pid=`echo $text | cut -c 1-$pos`
#echo pid=---$pid+++
echo ${pid}
return 0
}
get_mem()
{
process_id=$1
text=`cat /proc/$process_id/status | grep VmRSS`
#沒有這個進程
if [ "${text}" = "" ] ; then
memory=0
echo ${memory}
return 0
fi
pos=`expr index "$text" " "`
text=`echo $text | cut -c $pos-`
pos=`expr index "$text" " "`
pos=`expr $pos - 1`
memory=`echo $text | cut -c 1-$pos`
#echo memory=---$memory+++
echo ${memory}
return 0
}
# 最好是參數傳遞
PROCESS_NAME="quantum6"
pid=$(get_pid $PROCESS_NAME)
#沒有這個進程
if [ "${pid}" = "0" ] ; then
max_memory=0
else
max_memory=$(get_mem ${pid})
fi
echo pid=${pid}, max_mem=${max_memory}
# 循環。如果內存增加,輸出變化情況。
while [ true ] ; do
sleep 1s
# 得到進程號
pid=$(get_pid $PROCESS_NAME)
if [ "${pid}" = "0" ] ; then
# 沒找到,複位
max_memory=0
continue
fi
# 得到進程使用的內存。
current_memory=$(get_mem ${pid})
if [ "${current_memory}" = "0" ] ; then
continue
fi
# 如果佔用內存增加了,輸出
if [ ${current_memory} -gt ${max_memory} ] ; then
echo
echo ---------------------------------
date
diff=`expr ${current_memory} - ${max_memory}`
echo ${current_memory} - ${max_memory} = ${diff}
max_memory=${current_memory}
fi
done
輸出如下:
pid=15960, mem=3650724
---------------------------------
2019年 01月 07日 星期一 09:34:57 CST
3652832 - 3650724 = 2108
^C[quantum6@gh4ai gh4ai]$ ./check_mem.sh
pid=15960, mem=3650724
---------------------------------
2019年 01月 07日 星期一 09:35:32 CST
3651776 - 3650724 = 1052
---------------------------------
2019年 01月 07日 星期一 09:35:42 CST
3652832 - 3651776 = 1056
---------------------
作者:柳鯤鵬
原文:https://blog.csdn.net/quantum7/article/details/85985274
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


※那些年,被自己的技術者思維虐過的項目經理們
※HBase初識、CentOS6.6中HBase安裝與HBase Shell簡單使用
TAG:程序員小新人學習 |