tags:

views:

203

answers:

1

I'm not a scripting expert and I was wondering what was an acceptable way to run a script for at most x milliseconds (and yet finish before x milliseconds if the script is done before the timeout).

I solved that problem using Bash in a way that I think is very hacky and I wonder if there's a better way to do it.

Basically I've got one shell script called sleep_kill.sh that takes a PID as the first argument and a timeout as its second argument and that does this:

sleep $2
kill -9 $1 2> /dev/null 1> /dev/null

So if the PID corresponds to a script that finishes before timing out, nothing is going to be killed (I take it that the OS shall not have the time to be reusing this PID for another [unrelated] process seen that it's 'cycling' through all the process IDs before starting to reuse them).

Anyway, then I call my script that may "hang" or timeout:

command_that_may_hang.sh
PID=$!
sleep_kill.sh $PID .3
wait $PID > /dev/null 2>&1

And I'll be waiting at most 300 ms for command_that_may_hang.sh. Yet if command_that_may_hang.sh took only 10 ms to execute, I won't be "stuck" for 300 ms.

It would be great if some shell expert could explain the drawbacks of this approach and what should be done instead.

+1  A: 

Have a look at this script: http://www.pixelbeat.org/scripts/timeout Note timeouts of less that one second are pretty much nonsensical on most systems due to scheduling delays etc. Note also that newer coreutils has the timeout command included and it has a resolution of 1 second.

pixelbeat
+1, thanks a lot for your script but... Can you clarify why a timeout of less than one second (!?) is nonsensical? I use "sleep .1" all the time with my hack and it does definitely answers in close to 1/10th of a second: I've done tests printing dates in nanos (and anyway I clearly see a difference between a "sleep 1" and a "sleep .1"). How could video playback/sound players work on Linux if scheduling has not a better granularity than 1 second!? This sounds so weird in this day and age of high-precision timers and whatnots!? (I'm confused)
Webinator
Usually it's fine but sometimes there will be a delay and you'll time out the command erroneously. From experience in writing the coreutils tests running on various high powered but busy systems, a timeout of 3 seconds is the minimum found to not trigger erroneous timeouts.
pixelbeat