Bash 为什么当我的代码放在`/usr/bin/`中时,进程会停止得如此之快?

Bash 为什么当我的代码放在`/usr/bin/`中时,进程会停止得如此之快?,bash,resources,Bash,Resources,我试图创建一个命令,该命令对给定进程的内存使用和CPU时间使用施加一个硬限制,如果它超过这些限制,就杀死它。该命令还必须在进程结束时输出内存使用情况和CPU时间使用情况(无论进程是否被终止) 这是我的密码 # Get arguments MaxMemory="$1" MaxTime="$2" Command="$3" for (( i=4 ; i<="$#"; i++)); do Command="${Command} ${!i}" done echo -e "MaxMemory

我试图创建一个命令,该命令对给定进程的内存使用和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}"
该过程几乎在输出的瞬间停止

MaxMemory = 50000
MaxTime = 5000
Command = sleep 3s
pid = 31430
process has stopped
MEM 0 TIME 0
出了什么问题?

以下是您的输出:

Line 13:
${command} &
^-- SC2154: command is referenced but not assigned (for output from commands, use "$(command ...)" ).
您定义的变量使用大写字母C


但是,您应该真正使用
ulimit
而不是Wow shell检查听起来非常方便。我有点惭愧,错误如此简单。很抱歉,
ulimit
不适用于MAC OS的最新版本(请参阅)。至少它不适合我(我在MacOSX上)。
Line 13:
${command} &
^-- SC2154: command is referenced but not assigned (for output from commands, use "$(command ...)" ).