shell超时 输入超时-进程超时
20121031 Chenxin

1.使用多个shell进程的方式
用主程序执行调用子进程1的输入,然后调用子进程2的时间要求,当时间到达后,子进程2就kill掉子进程1,达到时间限制的效果;

2.使用read的-t参数
cat t.sh

echo "input char,in 3 seconds ..."
echo -n "[y/n] default [y]"
read -t 3 n
if [ -z $n ];then
n=y
fi

./t.sh
input char,in 3 seconds ...
[y/n] default [y]n
Your input char is: n

3.使用stty实现超时
stty -icanon min 0 time 100  #set 10seconds,not 100seconds
eval read varname  #=read $varname

4.一般的超时(摘自《shell脚本专家指南》P91)
cat t.sh

!/bin/bash

timeout()
{
waitfor= 2
command=$*
$command &
commandpid=$!
#echo "1 commandpid = $commandpid"

    (sleep $waitfor; kill -9 $commandpid > /dev/null 2>&1) &
    watchdogpid=$!
    #echo "2 watchdogpid = $watchdogpid"

    sleeppid=`ps $watchdogpid |awk '{ print $1}'`
    #echo "3 sleeppid = $sleeppid"

    wait $commandpid
    #echo "4 commandpid = $commandpid"

    kill $sleeppid > /dev/null 2>&1
    #echo "5 sleeppid = $sleeppid"

}
timeout ping 114.112.69.113 -c 5

程序执行ping操作,正常是5s的ping,在第2s后,就会被kill掉;如果在kill前已经自动结束了的话,则在wait $commandpid后,kill掉sleeppid;

相关文章:

  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2022-12-23
  • 2021-08-30
  • 2022-12-23
  • 2021-11-06
  • 2021-09-23
猜你喜欢
  • 2022-12-23
  • 2021-12-19
  • 2022-02-17
  • 2021-08-07
  • 2022-03-03
相关资源
相似解决方案