消耗Linux服务器内存的方法

需求:消耗指定大小的内存来提升服务器利用率或者验证服务器某些问题

1、使用C程序的方法

消耗指定大小的内存:cat malloc_mb.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
 
#define UNIT (1024*1024)
 
int main(int argc, char *argv[])
{
        long long i = 0;
        int size = 0;
 
        if (argc != 2) {
                printf(" === argc must 2\n");
                return 1;
        }
        size = strtoull(argv[1], NULL, 10);
        if (size == 0) {
                printf(" argv[1]=%s not good\n", argv[1]);
                return 1;
        }
 
        char *buff = (char *) malloc(size * UNIT);
        if (buff)
                printf(" we malloced %d Mb\n", size);
        buff[0] = 1;
 
        for (i = 1; i < (size * UNIT); i++) {
                if (i%1024 == 0)
                        buff[i] = buff[i-1]/8;
                else
                        buff[i] = i/2;
        }
        pause();
}
 
生成可执行小程序:
[root@web ~]# gcc malloc_mb.c -o mallocMb

[root@web ~]# free -m  #执行前内存情况
              total        used        free      shared  buff/cache   available
Mem:            974          83          68           2         822         709
Swap:          2047          69        1978

#执行这个可在系统中消耗掉100M的内存
[root@web ~]# nohup ./mallocMb 100 &  

[root@web ~]# free -m   #执行后内存情况
              total        used        free      shared  buff/cache   available
Mem:            974         182          76           2         715         610
Swap:          2047          69        1978

2、使用shell脚本的方法

shell脚本mem.sh消耗内存500M

#!/bin/bash

target="500M" #内存消耗目标:500M

# 消耗内存
start(){
    mkdir -p /tmp/memory
    mount -t tmpfs -o size=$target tmpfs /tmp/memory
    free -m
    dd if=/dev/zero of=/tmp/memory/block
    free -m
    sleep 2
}

#释放上面消耗的内存
stop(){
    rm -rf /tmp/memory/block
    umount /tmp/memory
    rmdir /tmp/memory
    if [ -d /tmp/memory ];then
        echo "无法移除目录 \"/tmp/memory\",请检查!"
    else
        echo "已移除消耗内存相关路径!"
    fi
}

case $1 in
    start)
        echo "开始执行消耗内存$target!"
        start
        ;;
    stop)
        stop
        ;;
    *)
        echo "Usage: <sh mem.sh start> or <sh men.sh stop>"
        ;;
esac

执行脚本

[root@web tmp]# sh mem.sh start
开始执行消耗内存500M!
              total        used        free      shared  buff/cache   available
Mem:            974          78         572           2         324         720
Swap:          2047          68        1979
dd: writing to ‘/tmp/memory/block’: No space left on device
1024001+0 records in
1024000+0 records out
524288000 bytes (524 MB) copied, 1.56195 s, 336 MB/s
              total        used        free      shared  buff/cache   available
Mem:            974          77          72         502         824         220
Swap:          2047          68        1979

# 需要释放内存使用下面命令
[root@web tmp]# sh mem.sh stop
已移除消耗内存相关路径!

猜你喜欢

转载自blog.csdn.net/change_can/article/details/118090293