vieyahn2017 / shellv

shell command test and study
4 stars 1 forks source link

check_timeout #95

Open vieyahn2017 opened 3 months ago

vieyahn2017 commented 3 months ago

check_timeout

vieyahn2017 commented 3 months ago
#后台监控自己是否超时的函数,如果到最大执行时间还没结束就认为超时,kill自己退出
function check_timeout {
    local process_id=$1   #传入要监控的进程号
    local max_second=$2   #超时时间,以秒为单位

    #该代码块在后台执行监控
    {
        local temp=""
        local timeout_flag=0
        for((i=0;i<${max_second};i++)); do
            temp=$(ps -ef  | grep -v grep | awk '{print $2}' | grep -e "^$process_id$")
            if [[ -z "${temp}" ]]; then
                timeout_flag=1
                break
            else
                sleep 1
            fi
        done

        if [[ "$timeout_flag" = "0" ]]; then
            local u_pid=$(ps -ef | grep -v grep | grep -e " ${process_id} " | grep userHealthCheck | awk '{print $2}')
            if [[ -n "${u_pid}" ]]; then
                kill -9 "${u_pid}"
                sleep 1
            fi
            kill -9 "${temp}"
        fi
    }&
}
vieyahn2017 commented 3 months ago

别的脚本


function main() {
    check_timeout "$$" "30"

    execute

}