【发布时间】:2018-08-12 15:24:39
【问题描述】:
我正在尝试创建一个命令,该命令对给定进程的内存使用和 CPU 时间使用施加硬限制,如果它超过这些限制,则将其杀死。该命令还必须在进程结束时输出内存使用情况和 CPU 时间使用情况(无论进程是否被杀死)。
这是我的代码。
# 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 given 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,pid | grep ${pid} | awk '{print $1}')
# Break if the process has stopped running
if [[ ${mem} == "" ]]; then
echo "process has stopped"
break
fi
# Set the MemoryPeak of memory
if (( MemoryPeak < mem )); then
MemoryPeak=mem
fi
# If it consumed too much memory, then kill
if (( MemoryPeak > 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 > 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}"
这里显示的代码exaclty放在/usr/bin/memAndTime的文件中,我用chmod授予它访问权限。当我在终端中设置参数并直接在终端上复制粘贴其余代码时,它似乎工作正常,但不知何故当我这样做时
memAndTime 50000 5000 sleep 3s
该过程几乎在输出的同时停止
MaxMemory = 50000
MaxTime = 5000
Command = sleep 3s
pid = 31430
process has stopped
MEM 0 TIME 0
出了什么问题?
【问题讨论】: