shell脚本超时控制

写脚本的时候,经常需要用到超时控制。看《shell专家编程》时看到一个好例子,收藏了~

#!/bin/sh
 
timeout()
{
        waitfor=3
        command=$*
        $command &
        commandpid=$!
 
        ( sleep $waitfor ; kill -9 $commandpid > /dev/null 2>&1 ) &
 
        watchdog=$!
        sleeppid=$PPID
        #原文中这句应该是有误,为什么要这么获取父进程ID?
        #sleeppid=`ps $ppid $watchdog |  awk '{print $1}'`
        #下面一行加上重定向是避免在被KILL的时候,报出被kill的提示
        #当然带来的副作用是重定向不一定符合预期
        wait $commandpid > /dev/null 2>&1 
 
        kill $sleeppid > /dev/null 2>&1
}
 
test123()
{
        sleep 10
}
 
timeout test123
原文地址:https://www.cnblogs.com/mfryf/p/3081480.html