I found some old code of mine and am trying to see if it can be improved. The goal is to write a command that measures a process's CPU time and RAM peak usage and kills the process if it exceeds a specified amount of CPU time and RAM usage.
This command is meant to be used on both MAC OSX and Linux.
# Get arguments
MaxMemory="$1"
MaxTime="$2"
Command="$3"
for (( i=4 ; i<="$#"; i++)); do
Command="${Command} ${!i}"
done
echo -e "MaxMemory = ${MaxMemory}\nMaxTime = ${MaxTime}\nCommand = ${Command}"
#### run the command in the background
${Command} &
#### Get pid
pid=$!
echo "pid = ${pid}"
#### Monitor resources
MemoryPeak=0
timeBefore=$(date +"%s")
while true;do
# Get memory
mem=$(ps -o rss= -p $pid)
# Break if the process has stopped running
if [[ ${mem} == "" ]]; then
break
fi
# Set the MemoryPeak of memory
if [ "${mem}" -gt "${MemoryPeak}" ]; then
MemoryPeak=$mem
fi
# If it consumed too much memory, then kill
if [ "${MemoryPeak}" -gt "${MaxMemory}" ];then
#echo "process consumed too much memory"
kill ${pid}
break
fi
# If it consumed too much CPU time, then kill
timeAfter=$(date +"%s")
timeUsage=$((timeAfter - timeBefore))
if [ "${timeUsage}" -gt "${MaxTime}" ];then
#echo "process consumed too much time"
kill ${pid}
break
fi
# sleep
sleep 0.1
done
timeAfter=$(date +"%s")
timeUsage=$((timeAfter - timeBefore))
echo "MEM ${MemoryPeak} TIME ${timeUsage}"
How can this be improved?