Search code examples
linuxtimeabort

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 fail it time > 4, but that's just a bad approach.

Thanks!


Solution

  • (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