cgroup使用 memory資源限制

2021-10-03 09:36:32 字數 2094 閱讀 8364

同樣,cgroup也可以對memory資源進行限制。下面以乙個例子來驗證cgroup對記憶體限制的使用。

1.編寫程式,迴圈分配600m記憶體。

#include

#include

#include

#define chunk_size 1024 * 1024 * 100

intmain()

memset

(p,0

, chunk_size)

;printf

("malloc memory %d mb\n"

,(i +1)

*100);

sleep(10

);}while(1

)return0;

}

2.編譯,執行程式

[root@localhost ~]

# gcc mem.c -o mem

[root@localhost ~]

# ./mem

malloc memory 100 mb

malloc memory 200 mb

malloc memory 300 mb

malloc memory 400 mb

malloc memory 500 mb

malloc memory 600 mb

[root@localhost ~]

# top -p 2265

pid user pr ni virt res shr s %cpu %mem time+ command

2265 root 20 0 618640 614744 388 s 0.0 15.9 0:00.47 mem

可以看出程式占用約600m記憶體。

3.新增cgroup限制

[root@localhost ~]

# mkdir -p /sys/fs/cgroup/memory/memory-test

[root@localhost ~]

# cat /sys/fs/cgroup/memory/memory-test/memory.limit_in_bytes

9223372036854771712

# 設定最大記憶體大小為200m

[root@localhost ~]

# echo 209715200 > /sys/fs/cgroup/memory/memory-test/memory.limit_in_bytes

[root@localhost ~]

# cat /sys/fs/cgroup/memory/memory-test/memory.limit_in_bytes

209715200

[root@localhost ~]

4.重新啟動程式,並將程式加入cgroup

[root@localhost ~]

# ./mem

#另乙個shell執行

[root@localhost ~]

# echo `ps -ef | grep mem | grep -v grep | awk ''` > /sys/fs/cgroup/memory/memory-test/tasks

過了一會可以看到程式被kill了。

[root@localhost ~]

# ./mem

malloc memory 100 mb

malloc memory 200 mb

killed

通過設定memory.oom_disable的值來設定記憶體超出設定值時是作業系統kill程序還是休眠程序。

# mem記憶體超過200m時程序會休眠

echo 1 > /sys/fs/cgroup/memory/memory-test/memory.oom_control

使用CGROUP限制mongd的disk io

使用cgroup做磁碟io的資源隔離,用到blkio子系統 先測試blkio限制dd的情況,很重要的一點是只能限制direct io,dd if dev zero of mongodb dd1 bs 4k count 10240 oflag direct 在測試mongod的時候,直接限制mongo...

使用cgroup限制磁碟io讀寫速率

在mysql innobackupex全備期間,磁碟io基本被打滿,設定過 throttle效果不明顯,throttle this option specifies a number of i o operations pairs of read write per second.it accept...

使用cgroup繫結程序到指定核

cgcreate g cpuset test cgset r cpuset.cpus 0test cgset r cpuset.mems 0test mems必須設定 cgexec g cpuset sunwg g1 python test.py 注 1.檢視linux文件發現cpuset子系統是有...