Showing posts with label init. Show all posts
Showing posts with label init. Show all posts

Saturday, October 28, 2006

shell: parallel execution with timeouts

From time in time I was looking how to run a command with a timeout (in a shell script). I never put big efford to find the solution, because I always found a easyer (and probably better) workaround. But few days ago, in a discussion in the austing group (POSIX standardization), I found the solution, in an elegant manner, and it permit also to run commands in parallel.

The solution (it works on bash, dash, and it seems posix compatible, but you should test, because the discussion was about the different behaviours of $! in bash and kornshell):
 # run command1 in background, and the sleeping killer
command1 &
pid=$!
( sleep 60; kill $pid ) &
# other stuffs
command2
# wait command1
wait $pid

Note: kill (the shell buildin) prints some error messages, which you should filter
Note: Security: the methods is not very clean and secure. If an user can force system to recycle the PID, the scripts could do unintended things.

I this trick can be used to parallel the init script (parallelize within the script, not "run scripts in parallel", as the current trend).
So another short tip: Debian sleep support "floating sleep", so use sleep .1 istead of sleep 1, to speed up the init scripts (module loading, waiting for devices, net,...). Unfortunately most of the debian scripts use integer sleeps.