Tuesday, February 8, 2011

How to run a Unix command for no more than a given amount of time

Here's my best attempt so far:

# /bin/sh
# timebomb - runs a command for a limited amount of time

#launch the assassin
./timebomb_assassin.sh $1 $2 &

# run the command
$2 $3 $4 $5 $6 $7 $8 $9

~~~~~~

# /bin/sh
# timebomb_assassin - kill a task by name after a given amount of time
# sleep for a while
sleep $1

# find the PID of the command (if it didn't terminate yet)

# Program to kill has the same PPID as us and an appropriate name.
TOKILL=`ps|sed 's/^I/ /'|awk "{if ($PPID == \\$2 && \\$0 ~ /.*$2/) print \\$1}"|tail -n 1`
if [ "$TOKILL" = "" ]; then
echo Seems liks $2 died by itself... > /dev/null
else
kill $TOKILL
fi

No comments:

Post a Comment