【问题标题】:Why does the process stops so quickly when my code is placed in `/usr/bin/`?当我的代码放在`/usr/bin/` 中时,为什么进程会这么快停止?
【发布时间】: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

出了什么问题?

【问题讨论】:

    标签: bash resources


    【解决方案1】:

    这是ShellCheck 的输出:

    Line 13:
    ${command} &
    ^-- SC2154: command is referenced but not assigned (for output from commands, use "$(command ...)" ).
    

    您定义的变量使用大写字母 C。

    但是,您确实应该改用ulimit

    【讨论】:

    • 哇,ShellCheck 听起来很方便。我有点惭愧,错误如此简单。恐怕 ulimit 不适用于 MAC OS 最新版本(请参阅 here)。至少它对我不起作用(我在 MAC OSX 上)。
    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 2011-04-06
    • 2011-05-27
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多