我写了一个简单的程序来限制它的数据大小为65Kb,并验证相同我分配一个超过65Kb的虚拟内存,逻辑上如果我正在做所有正确(如下)malloc调用应该失败,不是吗?
#include#include #include #include int main (int argc, char *argv[]) { struct rlimit limit; /* Get max data size . */ if (getrlimit(RLIMIT_DATA, &limit) != 0) { printf("getrlimit() failed with errno=%d\n", errno); return 1; } printf("The soft limit is %lu\n", limit.rlim_cur); printf("The hard limit is %lu\n", limit.rlim_max); limit.rlim_cur = 65 * 1024; limit.rlim_max = 65 * 1024; if (setrlimit(RLIMIT_DATA, &limit) != 0) { printf("setrlimit() failed with errno=%d\n", errno); return 1; } if (getrlimit(RLIMIT_DATA, &limit) != 0) { printf("getrlimit() failed with errno=%d\n", errno); return 1; } printf("The soft limit is %lu\n", limit.rlim_cur); printf("The hard limit is %lu\n", limit.rlim_max); system("bash -c 'ulimit -a'"); int *new2 = NULL; new2 = malloc(66666666); if (new2 == NULL) { printf("malloc failed\n"); return; } else { printf("success\n"); } return 0; }
令人惊讶的是,输出是这样的 -
The soft limit is 4294967295 The hard limit is 4294967295 The soft limit is 66560 The hard limit is 66560 core file size (blocks, -c) 0 data seg size (kbytes, -d) 65 scheduling priority (-e) 0 file size (blocks, -f) unlimited pending signals (-i) 14895 max locked memory (kbytes, -l) 64 max memory size (kbytes, -m) unlimited open files (-n) 1024 pipe size (512 bytes, -p) 8 POSIX message queues (bytes, -q) 819200 real-time priority (-r) 0 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 14895 virtual memory (kbytes, -v) unlimited file locks (-x) unlimited success
我做错了吗?请放弃您的输入.谢谢!
从setrlimit手册页:
RLIMIT_DATA
进程数据段的最大大小(初始化数据,未初始化数据和堆).此限制会影响对brk(2)和sbrk(2)的调用,这些调用在遇到此资源的软限制时会因错误ENOMEM而失败.
具体而言,该资源不适用于通过获取的内存mmap
.内部malloc
使用各种机制来获取新内存.在这种情况下,你会发现它使用mmap
而不是sbrk
或brk
.您可以通过从程序中转储系统调用来验证这一点strace
.
要实现您想要的功能,请使用RLIMIT_AS
资源.