原文:https://blog.csdn.net/mpu_nice/article/details/106918188
實現思想:借鑒虛擬內存的思想,創建虛擬內存文件系統,不斷寫入數據達到消耗內存的目的,需要清除內存時,刪除創建的虛擬內存目錄即可。
#使用虛擬內存構造內存消耗
mkdir /tmp/memory
mount -t tmpfs -o size=1024M tmpfs /tmp/memory
dd if=/dev/zero of=/tmp/memory/block
#釋放消耗的虛擬內存
rm /tmp/memory/block
umount /tmp/memory
rmdir /tmp/memory
下面的代碼為自己平時在測試過程中需要構造linux內存使用率的場景內存測試:
#!/bin/bash
# Destription: testing memory usage
# Example : sh memory_usage.sh 500M | sh memory_usage.sh 1G | sh memory_usage.sh release
FILE_NAME=`basename $0`
memsize=$2
function usage()
{
echo "Usage:$FILE_NAME consume memory_size|release -----the value of memory_size like 100M 2G and etc"
echo "Example: $FILE_NAME consume 1G"
echo " $FILE_NAME release"
}
function consume()
{
if [ -d /tmp/memory ];then
echo "/tmp/memory already exists"
else
mkdir /tmp/memory
fi
mount -t tmpfs -o size=$1 tmpfs /tmp/memory
dd if=/dev/zero of=/tmp/memory/block
}
function release()
{
rm /tmp/memory/block;ret=$?
if [ $ret != 0 ]; then
echo "remove memory data failed"
return $ret
fi
umount /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "umount memory filedir failed"
return $ret
fi
rmdir /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "remove memory filedir failed"
return $ret
fi
}
function main()
{
case "$1" in
consume) consume $memsize;;
release) release;;
*) usage;exit 1;;
esac
}
main $*
測試結果:
————————————————
版權聲明:本文為CSDN博主「mBeNice」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/mpu_nice/article/details/106918188