内存泄露很难查。

  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