If idql
uses CPU time in a loop when it gets hung, you can put a limit on its total CPU time:
( ulimit -t 5;
idql -n $REPOSITORY_NAME.$cs -Udmadmin -P"" -R$DM_SCRIPTS/test.api > /dev/null 2>&1 )
If idql
blocks for some other reason (e.g. a deadlock), you'll have to make that timeout on wall clock time. Here's a solution due to Stéphane Gimenez, lightly adapted to obtain the exit status of the idql
command.
ret=$(sh -ic '{ { idql -n "$REPOSITORY_NAME.$cs" -Udmadmin -P"" -R"$DM_SCRIPTS/test.api" > /dev/null 2>&1;
echo $? >&3;
kill 0; } |
{ sleep 5; kill 0; } }' </dev/null 3>&1 2>/dev/null)
if [ -z "$ret" ]; then
echo "timed out"
elif [ "$ret" -ne 0 ]; then
echo "error $ret"
else
echo "ok"
fi
Explanation:
- Start an interactive shell (
sh -i
). Since this shell is interactive, it is in its own process group.
- The subshell runs two commands piped together. This allows both commands to be executed in parallel inside the same process group.
- Both commands end with
kill 0
, which kills both all inside the process group. Whichever command ends first (idql
or sleep
) will thus kill the other one.
- Print the return status of
idql
to file descriptor 3, so that it doesn't go through the pipe. File descriptor 3 is redirected to file descriptor 1 in the outer shell, so that the output on that fd is captured by the command substitution.
- Redirect standard error of the interactive shell to
/dev/null
so as not to display any “Terminated” message from the inner shell. If you wanted to see the error output from idql
, you would need to redirect it (idql 2>&4
instead of idql 2>/dev/null
, and add 4>&2
before the 2>/dev/null
of sh -i
).
- Redirect standard input of the interactive shell from
/dev/null
so that it doesn't end up reading commands from the terminal if you press Ctrl+C.
timeout
ksh: timeout: not found
bash: timeout: command not found
– Vishnu Sep 07 '12 at 07:31timeout
is a Linux-specific command (more precisely: specific to GNU coreutils). People who write ksh are usually working on some unix other than Linux and BSD. – Gilles 'SO- stop being evil' Sep 07 '12 at 20:42