【问题标题】:setrlimit doesn't work on restricting the maximum amount of memorysetrlimit 不适用于限制最大内存量
【发布时间】:2017-02-25 01:47:33
【问题描述】:

我正在使用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

【问题讨论】:

    标签: resources setrlimit


    【解决方案1】:

    不,您的代码没有任何问题。假设RLIMIT_ASmalloc()立即 影响,你是错误的。简而言之,后者(通常有很多变体)使用brk() 从堆中以块的形式分配其后备内存,或者使用mmap() 分配按需映射的页面,然后将这些块划分为单独的分配。很有可能已经在堆中分配了足够的空间来满足您的malloc() 调用,而您的新RLIMIT_AS 只会影响对brk()mmap() 的后续调用。总而言之,这是完全正常的。

    【讨论】:

    • 以及如何强制执行限制,以使上面的代码不会通过,而是因错误而失败?
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多