Tuesday, September 17, 2013

Script to kill the command with timeout.

If you don't bother to wait the command to timeout. You can have a bash script as a wrapper to clean the PID within your defined timeout values. I came across the same function like this before in my senior codes, just can't recall how is the codes goes. Now, I am totally rewrite it based on my memory. Hope that it can help you when doing bash coding.

function run_with_command () {
CMD=$1
TIMEOUT=$2
COUNTER=0
${CMD} &
CMD_PID=$!
while ps $CMD_PID > /dev/null && [ $COUNTER -lt $TIMEOUT ]; do
sleep 1
COUNTER=$((COUNTER+1))
done


if [ $COUNTER -eq $TIMEOUT ]

then
kill $CMD_PID 2>/dev/null
fi


wait $CMD_PID 2>/dev/null

}

No comments: