前天写了个监控程序结束时间的脚本,现在又增加了一些功能,可以查看程序所占用的内存、CPU等,需要更多的信息,加入相应命令即可。
#!/bin/bash
# 指定写入的txt文件
log_file="./xxx.txt"
# 写入脚本开始运行时的时间
echo "start time : `date "+%Y-%m-%d %H:%M:%S"`" > $log_file
# 定义常量
flag=1
interval=1
count=0
# 进入循环
while [ "${flag}" -eq 1 ]
do
# 打印循环次数
count=$((count+1))
echo ${count} >> $log_file
# 查询程序PIDxxxx
PID=`pidof xxxx`
# 根据程序PID查询内存占用,并追加写入文档
RES=`cat /proc/${PID}/status | grep -e VmRSS`
echo "RES : ${RES}" >> $log_file
# 根据程序PID分别查询CPU占用和内存占用百分比,并分别追加写入文档(-f不同的值有不同的查询字段)
CPU=`top -b -n 1 -d 1 | grep ${PID} | cut -d " " -f18`
echo "CPU : ${CPU}" >> $log_file
MEM=`top -b -n 1 -d 1 | grep ${PID} | cut -d " " -f20`
echo "MEM : ${MEM}" >> $log_file
# 检测到PID长度为零则退出循环,程序结束
if [ -z "$PID" ]
then
echo "stop time:`date "+%y-%m-%d %H:%M:%S"`" >> $log_file
flag=0
fi
# 根据需求自定义睡眠时间,以免txt文件过长
sleep ${interval}
done