我正在尝试使用 cgroups 来停止实际使用过多内存的程序,同时让它们运行,如果它们只是分配而不实际使用大量内存。但是,它似乎不起作用;有什么建议么?在 Ubuntu 机器上,我按如下方式设置我的 cgroup[1]:
#Changing $USER to a system user running the process
sudo apt-get install cgroup-bin
sudo cgcreate -a $USER -g memory:$USER
echo 100M > /cgroup/memory/$USER/memory.limit_in_bytes
#Running the program using cgroups
cgexec -g memory:$USER program
我正在使用以下程序(回答“否”应该有效,而"is"应该停止)。
#include <stdlib.h>
#include <stdio.h>
#define SIZE (long int) 1*1024*1024*1024*sizeof(char)/*1 GB*/
int main(void)
{
char *str = (char*) malloc(SIZE);
char *ans = (char*) malloc(100);
printf("Write random values to memory? (yes/no): ");
scanf("%s", ans);
if (strcmp(ans,"yes") == 0) {
FILE *f = fopen("/dev/urandom","r");
fread(str,1,SIZE,f);
printf("Success!!\n");
fclose(f);
free(str);
}
else {
printf("Have a good day!\n");
}
return(0);
}
最佳答案
您的测试返回成功,因为它没有检查错误。事实上,当您的二进制文件达到内存限制时, fread 调用分配失败。 您可以通过更改代码来检查错误来看到这一点:
#include <stdlib.h>
#include <stdio.h>
#define SIZE (long int) 1*1024*1024*1024*sizeof(char)/*1 GB*/
int main(void)
{
char *str = (char*) malloc(SIZE);
char *ans = (char*) malloc(100);
printf("Write random values to memory? (yes/no): ");
scanf("%s", ans);
if (strcmp(ans,"yes") == 0) {
FILE *f = fopen("/dev/urandom","r");
int size = fread(str,1,SIZE,f);
if (size < SIZE) {
printf("incomplete read: %d, error %d\n", size, ferror(f));
} else {
printf("Success!!\n");
}
fclose(f);
free(str);
}
else {
printf("Have a good day!\n");
}
return(0);
}
更酷的是使用 cgroup 监控实用程序,如 cadvisor您可以以图形方式看到您的二进制文件达到了极限。 .希望有所帮助:)
关于linux - 在 Linux 上使用 cgroups 控制内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843537/