Is there a way to provide a max execution time to a program when I launch it? Here is what I am doing now
Code:
## c --> each students' name
## hw --> name of executable
MAX_NUM_HOURS="2" ## arbitrary upper bound
## time a detached program
/usr/bin/time -f "%E real,%U user,%S sys" --output="${c}_Time.txt" --append ./${hw} > {c}_output.txt &
#Kill program after running for specified hours
DONE=0
while [ $DONE -eq 0 ]; do
/bin/sleep 1s # sleep for a second
elapsedTime=`ps -e | grep ${hw} | awk '{print $3}'`
if [ -z $elapsedTime ]; then # finished before time limit
DONE=1
else # kill if running too long
hours=`echo $elapsedTime | cut -d":" -f1`
if (("$hours" >= "$MAX_NUM_HOURS")); then
echo "Killing program, running too long"
/bin/kill `pidof ${hw}` &> /dev/null
DONE=1
fi
fi
done
As you see, I run the students' code detached, and start a while loop monitoring the execution, killing their code if it is taking too long. Is there a better way?
Bookmarks