I wrote a function to run commands, which takes two args 1st a command 2nd timeout in seconds:
#! /bin/bash
function run_cmd {
cmd="$1"; timeout="$2"
grep -qP "^\d+$" <<< "$timeout" || timeout=10
stderrfile=$(readlink /proc/$$/fd/2)
exec 2<&-
exitfile=/tmp/exit_$(date +%s.%N)
(eval "$cmd";echo $? > $exitfile) &
start=$(date +%s)
while true; do
pid=$(jobs -l | awk '/Running/{print $2}')
if [ -n "$pid" ]; then
now=$(date +%s)
running=$(($now - $start))
if [ "$running" -ge "$timeout" ];then
kill -15 "$pid"
exit=1
fi
sleep 1
else
break
fi
done
test -n "$exit" || exit=$(cat $exitfile)
rm $exitfile
exec 2>$stderrfile
return "$exit"
}
function sleep5 {
sleep 5
echo "I slept 5"
return 2
}
run_cmd sleep5 "6"
run_cmd sleep5 "3"
echo "hi" >&2
The function works fine but I am not sure it's an elegant solution, I would like to know about alternatives for the following
- I am having to store exit status on a file:
(eval "$cmd";echo $? > $exitfile)
- I am closing and reopening STDERR:
exec 2<&- and exec 2>$stderrfile
I am closing STDERR because I couldn't avoid the message when killing the command:
test.sh: line 3: 32323 Terminated ( eval "$cmd"; echo $? > $exitfile )
PS: I am aware of timeout
and expect
but they wouldn't work for functions.