linux - 在 Linux 上使用 cgroups 控制内存使用

标签 linux memory-management process cgroups

我正在尝试使用 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); 
}

[1] https://askubuntu.com/questions/94619/how-to-set-cpu-limit-for-given-process-permanently-cpulimit-and-nice-dont-work

最佳答案

您的测试返回成功,因为它没有检查错误。事实上,当您的二进制文件达到内存限制时, 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您可以以图形方式看到您的二进制文件达到了极限。 cadvisor .希望有所帮助:)

关于linux - 在 Linux 上使用 cgroups 控制内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28843537/

相关文章:

C++ 对象实例在被销毁后保留在列表中

xcode - cocoa 应用程序 : How to find running process

delphi - 为什么 EnumProcesses 中的参数 aProcesses 设置为 1024?

C++ map 添加新元素

Linux 内核导出符号

linux - 适合初学者的嵌入式 Linux

c - 尝试释放内存时出现堆错误

linux - 拥有 root 用户的进程是否始终拥有 Linux 中可用的所有功能?

r - 用于重复距离矩阵计算和超大距离矩阵分块的高效(内存方面)函数

C#通过进程通过cmd调用带有错误重定向和exe的批处理