有个libreoffice服务,正常情况下运行几秒钟就会自动结束,但是有时候因为机器资源占用过多、或机器配置太低等原因会导致该进程僵死,这样下次调用该业务时会有影响,所以需要将该服务运行时间超过5分钟的进程杀掉。
1.通过ps获取该服务的PID和运行时间;
2.判断运行时间是否超过5分钟(这里转换为300秒了);
3.根据判断结果确定是否杀掉进程;
4.通过crontab定时执行该脚本;
- #!/usr/bin/bash
- pro_name=libreoffice
- username=`whoami`
- interval=300
- #pro=`ps -eo pid,user,etime,cmd | grep ${pro_name} |grep -v grep | awk '{pid=$1;user=$2;etime=$3 ; print pid,etime ; }'`
- ps -eo pid,user,etime,cmd | grep ${pro_name} |grep -v grep | awk '{pid=$1;user=$2;etime=$3 ; print pid,etime ; }' | while read LINE
- do
- #获取进程PID
- pid=`echo $LINE | awk '{print $1}'`
- #获取程序运行时间,单位为秒,超过60分钟则设置为默认值99999999999999
- elapsed=`echo $LINE | awk -F: 'BEGIN {
- time=99999999999999;
- }
- {
- if(NF>=3){
- print time;
- }else if(NF>=2){
- time=$(NF-1)*60+$NF;print time
- }else{
- print "error format"
- }
- }'`
- #判断程序运行的时间是否超过指定周期$interval
- if [ $elapsed -ge $interval ];then
- echo "$LINE"
- kill -9 $pid
- fi
- done
- #每隔2分钟执行一次
- */2 * * * * sh /root/kill_service.sh