Skip to content

Instantly share code, notes, and snippets.

@damonYuan
Created January 21, 2019 14:07
Show Gist options
  • Select an option

  • Save damonYuan/6a55fd6f14ab488de899525fb38f50ef to your computer and use it in GitHub Desktop.

Select an option

Save damonYuan/6a55fd6f14ab488de899525fb38f50ef to your computer and use it in GitHub Desktop.
memory leakage detection
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment