#!/bin/sh
#程序名称 - 可自定义
app_name='TestApp'
#进程名称
process_name='TestApp'
#运行超时时间(秒)
process_timeout=10
#最大进程数
max_process_num=1
#定时清理时间(MMDD,例如23点59分=2359)
clean_time=2337
#巡检休眠时间(秒)
sleep_seconds=10
#检验任务运行时间并清理
function check_time()
{
time_subroutine=$(getconf CLK_TCK)
start_time=$(awk '{print $22}' /proc/$1/stat)
sys_uptime=$(awk '{print $1}' /proc/uptime)
pid_uptime=$((${sys_uptime%.*} - ${start_time}/${time_subroutine}))
if [ ${pid_uptime} -ge $2 ];then
kill -9 $1
echo "$(date):进程ID为 [$1] 的进程 [$app_name] 已经运行了 ${pid_uptime} 秒 ,大于超时时间 [$2] 秒, 清理!"
fi
}
while true
do
for app_num in $(ps -ef|grep $process_name|grep -v grep|awk -F ' ' '{print $2}'|wc -l)
do
if [ ${app_num} -gt $max_process_num ];then
echo "$(date):[$app_name] 进程数量为 [${app_num}] ,符合设定数量 [$max_process_num] , 开始清理超过 [$process_timeout] 秒的程序."
for pid in $(ps -ef |grep $process_name|grep -v grep|awk '{print $2}')
do
check_time $pid $process_timeout
done
else
echo "$(date):[$app_name] 进程数量为 [${app_num}] ,不高于设定数量 [$max_process_num] ,不操作."
fi
done
curHourMin=$(date -d now "+%H%M")
if [ $curHourMin -eq $clean_time ];then
echo "$(date):[$app_name] 运行超过 [$process_timeout]秒!"
for pid in $(ps -ef |grep $process_name|grep -v grep|awk '{print $2}')
do
check_time $pid $process_timeout
done
fi
sleep $sleep_seconds
done