cgroup的使用 - 549642238/linux-stable GitHub Wiki
CGroupRef是Control Groups的缩写,是Linux内核提供的一种可以限制、记录、隔离进程组(process groups)所使用的物理资源(如cpu、memory、i/o等等)的机制。只要在/sys/fs/cgroup中创建目录,然后将需要约束的进程或进程组写入cgroup.procs就可以对其内存、CPU等资源的使用做限制
Example 1. 使用cgroup限制进程组使用的内存Ref
准备内存占用的测试用例
// /root/eat_mem.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MB (1024 * 1024)
int main(void)
{
char *p;
int i = 0;
while (1) {
p = (char *)malloc(1 * MB);
memset(p, 0, 1 * MB);
i += 1;
printf("%dMB memory allocated\n", i);
usleep(3000);
}
return 0;
}
配置cgroup,消耗内存触发OOM
$ cd /sys/fs/cgroup/memory # 限制内存
$ mkdir test # 创建新的cgroup组
$ cd test
$ echo 10M > memory.limit_in_bytes # 限制test组下的任务组占用内存不得超过10M
$ echo $$ > cgroup.procs # 当前bash进程id以及子进程都属于test cgroup
$ /root/eat_mem # 运行测试用例
1MB memory allocated
2MB memory allocated
3MB memory allocated
4MB memory allocated
5MB memory allocated
6MB memory allocated
7MB memory allocated
8MB memory allocated
9MB memory allocated
Killed
[ 351.993343] Memory cgroup out of memory: Kill process 2949 (eat_mem) score 1080 or sacrifice child