2016-10-15 67 views
0

我正在学习使用setrlimitgetrlimit的linux资源控制。这样做是为了限制可用于给定过程的存储器的最大量:setrlimit不能限制最大内存量

#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

不,你的代码没有问题。假设RLIMIT_ASmalloc()具有直接的影响只是错误的。简而言之,后者(通常有许多变体)以brk()或按需映射的页面与mmap()分块分配其后备内存,然后将这些块分割成单独的分配。有可能在堆中分配了足够的空间以满足您的malloc()呼叫,而您的新RLIMIT_AS只会影响后续呼叫brk()mmap()。总而言之,这是完全正常的。