setrlimit不能限制最大内存量

时间:2016-10-15 19:24:31

标签: resources setrlimit

我正在使用setrlimitgetrlimit学习linux资源控制。我们的想法是限制可用于给定进程的最大内存量:

#include <sys/resource.h> 
#include <sys/time.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main () 
{ 
  // Define and object of structure 
  // rlimit. 
  struct rlimit rl; 

  // First get the limit on memory 
  getrlimit (RLIMIT_AS, &rl); 

  printf("\n Default value is : %lld\n", (long long int)rl.rlim_cur); 

  // Change the limit 
  rl.rlim_cur = 100; 
  rl.rlim_max = 100; 

  // Now call setrlimit() to set the  
  // changed value. 
  setrlimit (RLIMIT_AS, &rl); 

  // Again get the limit and check 
  getrlimit (RLIMIT_AS, &rl); 

  printf("\n Default value now is : %lld\n", (long long int)rl.rlim_cur); 

  // Try to allocate more memory than the set limit 
  char *ptr = NULL; 
  ptr = (char*) malloc(65536*sizeof(char)); 
  if(NULL == ptr) 
  {   
      printf("\n Memory allocation failed\n"); 
      return -1; 
  }   

  printf("pass\n");

  free(ptr); 

  return 0;  
}

上面的代码将内存限制为100个字节(软和硬)。但是,malloc仍会返回而不会出错。代码有什么问题吗?我得到的输出是:

Default value is : -1
Default value now is : 100
pass

1 个答案:

答案 0 :(得分:1)

不,你的代码没有错。您认为RLIMIT_ASmalloc()上具有立即效果是错误的。简而言之,后者(通常有很多变体)在堆中使用brk()或按需映射的页面mmap()分配其后备内存,然后将这些块分成单独的分配。很可能在堆中已经分配了足够的空间来满足您的malloc()呼叫,而新的RLIMIT_AS只会影响brk()mmap()的后续呼叫。总而言之,这是完全正常的。