提高服务器cpu、内存负载脚本

!/bin/bash

FILE_NAME=basename $0
cpunum=$2
pid_array=()
function usage()
{
echo “Usage:$FILE_NAME consume cpu_number|release —–the value of cpu_number is an integer,such as 1,2,3”
echo “Example: $FILE_NAME consume 12”
echo ” $FILE_NAME release”
}

function endless_loop()
{
echo -ne “i=0;
while true
do
i=i+100;
i=100
done” | /bin/bash &
}

function consume()
{
for i in seq $1
do
endless_loop
pid_array[$i]=$!
done
echo “consume cpu resources process ids are: ${pid_array[]}” echo “${pid_array[]}” >/opt/c.pid
}

function release()
{
for pid in $(cat /opt/c.pid)
do
kill -9 $pid
done
}

function main()
{
case “$1” in
consume) consume $cpunum;;
release) release;;
*) usage;exit 1;;
esac
}

main $*

#启动: sh c.sh consume 2

#参数2:占满2核

#停止: sh c.sh release

内存脚本:

将内存泄露程序memory-process上传到服务器/opt/目录下

vim /usr/lib/systemd/system/mem-process.service

[Unit]
Description=Systemd memmory resource limit test

[Service]
ExecStart=/opt/memory-process -d 5 -l 90
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=always
MemoryLimit=100M

[Install]
WantedBy=multi-user.target

解释:

ExecStart=/opt/memory-process -d 5 -l 90 #90为设定的内存泄露程序占用内存,单位MB MemoryLimit=100M #这里强限制为100M防止内存泄露程序出现不可知问题,通常要比上边90大,防止程序出现OOM。

#启动: systemctl start mem-process.service

#停止: systemctl stop mem-process.service