2016-10-15 66 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()。總而言之,這是完全正常的。