使用 shell 脚本对 Linux 系统和进程资源进行监控(3)
function GetMem { MEMUsage=`ps -o vsz -p $1|grep -v VSZ` (( MEMUsage /= 1000)) echo $MEMUsage } |
下面的功能是通过上面的函数 GetMem
获得此进程的内存使用,然后通过条件语句判断内存使用是否超过限制,如果超过 1.6G(可以根据实际情况进行调整),则输出告警,否则输出正常信息。
mem=`GetMem $PID` if [ $mem -gt 1600 ] then { echo “The usage of memory is larger than 1.6G” } else { echo “The usage of memory is normal” } fi |
示例演示:
1)源程序(假设上面已经查询出 CFTestApp 的进程 ID 为 11426)
mem=`GetMem 11426` echo "The usage of memory is $mem M" if [ $mem -gt 1600 ] then { echo "The usage of memory is larger than 1.6G" } else { echo "The usage of memory is normal" } fi |
2)结果输出
The usage of memory is 248 M The usage of memory is normal [dyu@xilinuxbldsrv shell]$ |
3)结果分析
从上面的输出可见:CFTestApp 程序当前的内存使用为 248M,是正常的,没有超过 1.6G 的告警限制。
在对应用服务进行维护时,也经常遇到由于句柄使用 过量导致业务中断的情况。每个平台对进程的句柄使用都是有限的,例如在 Linux 平台,我们可以使用 ulimit – n 命令(open files (-n) 1024)或者对 /etc/security/limits.conf 的内容进行查看,得到进程句柄限制。句柄使用过高可能由于负载过高,句柄泄露等情况,通过脚本对业务进程句柄使用量进行时时监控,可以在异常时及时发送告警(例如通过短信),便于维护人员及时处理。下面的函数可获得指定进程 ID 的进程句柄使用情况。它有一个参数为进程 ID,它首先使用 ls 输出进程句柄信息,然后通过 wc -l 统计输出句柄个数。
function GetDes { DES=`ls /proc/$1/fd | wc -l` echo $DES } |
下面功能是通过上面的函数 GetDes
获得此进程的句柄使用量,然后通过条件语句判断句柄使用是否超过限制,如果超过 900(可以根据实际情况进行调整)个,则输出告警,否则输出正常信息。
des=` GetDes $PID` if [ $des -gt 900 ] then { echo “The number of des is larger than 900” } else { echo “The number of des is normal” } fi |
示例演示: