因为项目的问题,时不时会出现多个超时运行进程,影响系统运行。
写了一个杀进程的脚本,然后定时去执行它。
1 编写杀进程的脚本 /root/kill_service.sh
#!/usr/bin/bash
# 检查tesseract 进程,如果超过30秒,就把它kill掉
# 该程序需要写入定时任务(每10分钟运行一次)
# 每隔10分钟执行一次
# */10 * * * * sh /root/kill_service.sh
# 需要监控的进程名称(例如tesseract)
pro_name=tesseract
# 进程归属的用户
username=root
# 超时时间30秒(假定认为该进程超过30秒,就认为该进程超时,需要kill掉)
interval=30
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}'`
#获取程序运行时间,
miao=`echo $LINE | awk -F: '{print $2}'`
fen=`echo $LINE | awk -F: '{print $1}' | awk -F' ' '{print $2}'`
let "second=miao+fen*60"
#判断进程运行的时间是否超过指定周期$interval
if [ $second -ge $interval ];then
echo "555 $LINE kill $elapsed second $etime ssss"
# 杀死该进程
kill -9 $pid
fi
done
2. 设定时任务,定时执行上面的脚本
切换到root 用户下运行
#查看定时任务
crontab -l
#编辑定时任务
vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
#每隔2分钟执行一次
*/2 * * * * sh /root/kill_service.sh &>> /root/log/kill_service.log
# 启动定时任务
crontab /etc/crontab