Just for reference, this is really useful:
( cmdpid=$BASHPID; (sleep 10; kill $cmdpid) & exec some_command ) |
Update Apr 20, 2012 @ 16:54: As pointed in a comment by Timo Juhani Lindfors, if “some_command” exits early and the interval is long, another process can reuse its process number and get killed once the sleep runs out. Does anybody know a better way of doing that without using timeout from coreutils (better yet: using just bash)?










The secret is to be the parent:
some_command & child_pid=$!
trap true ALRM
parent_pid=$$
(sleep 10 && kill -ALRM $parent_pid) & alarm_pid=$!
wait $child_pid
if [ $? -gt 128 ]; then
# timed out
kill $child_pid
else
# cancel timeout
kill $alarm_pid
fi
As a bonus, this works in dash and probably any POSIX shell.
@Ben,
Yep… but that is much longer and hard to remember than a single line. But good point: be the parent and the pid will not be reused.
There’s killall if you don’t mind killing all processes with that name.
if some_command exits before 10 seconds isn’t there the problem that the pid could get reused and you would kill a completely unrelated process?
@Timo,
Actually the problem you described will happen. I guess if we’re talking about a 10 seconds timeout, hardly the process number will be reused. But if the timeout is larger, that will happen.
the command “timeout 10s command” will do the job too
Sure. But a little bash, subshell, and process trickery are much more fun
And this is helpful in the case the coreutils version does not include the timeout command.
true, I had the problem in an ubuntu install
…so you install the timelimit package and no more problems
)
(ok, this *was* a shameless plug, and a couple of months late, too