开发者

Abort a program after a certain time

I'm trying to develop a test case for a program, and would like to fail the test case if it runs over 4 seconds. How can this be done on linux? (I'm using Ubuntu)

I know I can time the execution and f开发者_运维问答ail it time > 4, but that's just a bad approach.

Thanks!


(shell script solution) Runs your testcase in background, get the PId of it, and checks after 4 seconds if the process is still running.

wait_seconds=4
interval_seconds=0.5
run_your_test_case &
pid=$!
max=`expr "$wait_seconds / $interval_seconds"`
for (( I=0; I<$max; I++ ));do
    if kill -0 $pid >/dev/null;then
       echo 'test failed'
    else
       echo 'test ok'
       break
    fi
    sleep $interval_seconds
done


Final solution:

  1 ./slowprogram.sh >/dev/null &
  2 pid=$!
  3 exitbreak=0
  4 for c in {0..4}; do
  5         sleep 1
  6         kill -0 $pid 2>/dev/null
  7         if [ $? -ne 0 ] ;then
  8             exitbreak=1
  9             break
 10         fi
 11 done
 12 if  [ $exitbreak == 1 ]; then
 13         echo '[ OK ]'
 14 else
 15         echo '[FAIL]'
 16         kill -9 $pid 2>/dev/null 
 17 fi


You could also do something like <command> & sleep 5 && kill ${!}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜