LINUX檢查一個進程內存增長的腳本

內存泄露很難查。

  1、內存有沒有泄露?

  2、內存在哪裏泄露?

  爲了解決第一個問題,吾絞盡腦汁,寫了一個腳本,檢查特定程序的內存增長。即只要增長就會輸出。分享出來供大家參考。

# ps -A | grep ${PROCESS_NAME} | awk '{print $1}'
get_pid()
{
    process_name=$1
    text=`ps -A | grep $process_name`
    # 去掉開頭的空格
    text=`echo $text | sed -e 's/^[ \t]*//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
}
 
# cat /proc/${pid}/status | grep VmRSS | awk '{print $2}'
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"
 
# 有人指點,也可以一條命令搞定:
# ps -A | grep ${PROCESS_NAME} | awk '{print $1}'
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
 
    # 得到進程使用的內存。
    # cat /proc/${pid}/status | grep VmRSS | awk '{print $2}'
    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
 
--------------------- 
作者:柳鯤鵬 
來源:CSDN 
原文:https://blog.csdn.net/quantum7/article/details/85985274 
版權聲明:本文爲博主原創文章,轉載請附上博文鏈接!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章