简体   繁体   English

mmap()在1TB ANONYMOUS文件中使用ENOMEM失败?

[英]mmap() fail with ENOMEM on a 1TB ANONYMOUS file?

I'm trying to mmap an 1TB anonymous file under Fedora Linux x86_64 (4G RAM plus 16G swap). 我正在尝试在Fedora Linux x86_64(4G RAM加16G交换)下mmap一个1TB匿名文件。 But I got ENOMEM "cannot allocate memory" and even for 32G as the following code. 但我得到ENOMEM“无法分配内存”,甚至为32G作为以下代码。 Am I missing anything? 我错过了什么吗? Appreciate any clue. 感谢任何线索。

#define HEAP_SIZE (1UL << 35)
int main()
{
    void *addr = mmap(0, HEAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    if (addr == MAP_FAILED)
    {
        perror(NULL);
        return 1;
    }
    printf("mmap %d gbytes succeed\n", HEAP_SIZE/(1UL << 30));
    return 0;
}

The default Linux overcommit policy prevents you from allocating this much memory. 默认的Linux overcommit策略会阻止您分配这么多内存。 You don't have anywhere near 1TB of RAM, and the kernel will give you ENOMEM now rather than running the OOM killer later... but you can change this policy. 你没有接近1TB的RAM,内核现在会给你ENOMEM而不是以后运行OOM杀手......但是你可以改变这个策略。

$ /sbin/sysctl vm.overcommit_memory
vm.overcommit_memory = 0
$ sudo /sbin/sysctl vm.overcommit_memory=1
vm.overcommit_memory = 1

Policy 1 is "always overcommit", which is useful for certain applications. 策略1“总是过度使用”,这对某些应用程序很有用。 Policy 2 is "never overcommit". 政策2“永远不会过度使用”。 The default policy, 0, allows some overcommit but uses heuristics to reject large allocations, like the one which failed on your computer. 默认策略0允许一些过度使用,但使用启发式方法拒绝大型分配,例如计算机上出现故障的分配。

Alternative 替代

You could also use the MAP_NORESERVE flag. 您还可以使用MAP_NORESERVE标志。 Note that the kernel will ignore this flag if its policy is to "never overcommit". 请注意,如果内核的策略是“永远不会过度使用”,内核将忽略此标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM