柳鲲鹏
获取某程序名的进程号,显示其内存占用情况。代码如下:
get_pid() { process_name=$1 text=`ps -A | grep $process_name` # 去掉开头的空格 text=`echo $text | sed -e 's/^[ \t]*//g'` # 得到进程号之后的空格 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` 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="gh_main" pid=$(get_pid $PROCESS_NAME) old_memory=$(get_mem $pid) echo pid=$pid, mem=$old_memory # 循环。如果内存变化,输出变化情况。 while [ true ] ; do new_memory=$(get_mem $pid) if [ $new_memory -ne $old_memory ] ; then # 便于观察 echo echo --------------------------------- date diff=`expr $new_memory - $old_memory` echo $old_memory - $new_memory = $diff old_memory=$new_memory fi done