小编典典

编写一个bash shell脚本,该脚本在用户定义的时间内消耗恒定数量的RAM。

linux

我正在尝试编写一个bash shell脚本,该脚本在用户定义的时间内消耗嵌入式设备上的大量RAM。不使用数组怎么办?


阅读 293

收藏
2020-06-02

共1个答案

小编典典

即使不支持传统的Bash数组,也仍然可以使用eval特定Shell中内置的命令来创建类似数组的变量。

以下示例脚本基于我在嵌入式Linux项目中使用BusyBox时执行的一些脚本。
BusyBox使用Almquist
Shell
(也称为A Shell,ash和sh),它不支持数组。

#!/bin/ash

for index in 1 2 3 4 5; do
    value=$(($index * 1024))
    eval array$index=\"array[$index]: $value\"
done

for i in 1 3 5; do
    eval echo \$array$i
done

使用时请小心报价eval

输出:

array[1]: 1024
array[3]: 3072
array[5]: 5120

根据您的特定情况,类似于以下内容的脚本可能就足够了。

#!/bin/ash

echo "Provide sleep time in the form of NUMBER[SUFFIX]"
echo "   SUFFIX may be 's' for seconds (default), 'm' for minutes,"
echo "   'h' for hours, or 'd' for days."
read -p "> " delay

echo "begin allocating memory..."
for index in $(seq 1000); do
    value=$(seq -w -s '' $index $(($index + 100000)))
    eval array$index=$value
done
echo "...end allocating memory"

echo "sleeping for $delay"
sleep $delay

在我的简短测试中,此脚本在指定的5分钟时间段内消耗了约570M至〜575M的物理内存*。

*在单独的测试中使用top和memprof程序进行监视

2020-06-02