我正在学习使用setrlimit
and的 linux 资源控制getrlimit
。这个想法是限制可用于给定进程的最大内存量:
#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