为什么mmap无法分配内存?

前端之家收集整理的这篇文章主要介绍了为什么mmap无法分配内存?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用root权限运行程序,但它一直在抱怨mmap无法分配内存.代码段如下:
  1. #define PROTECTION (PROT_READ | PROT_WRITE)
  2. #define LENGTH (4*1024)
  3.  
  4. #ifndef MAP_HUGETLB
  5. #define MAP_HUGETLB 0x40000
  6. #endif
  7.  
  8. #define ADDR (void *) (0x0UL)
  9. #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB)
  10.  
  11. int main (int argc,char *argv[]){
  12. ...
  13. // allocate a buffer with the same size as the LLC using huge pages
  14. buf = mmap(ADDR,LENGTH,PROTECTION,FLAGS,0);
  15. if (buf == MAP_Failed) {
  16. perror("mmap");
  17. exit(1);
  18. }
  19. ...}

硬件:我有8G内存.处理器是ivybridge

Uname输出

  1. Linux mymachine 3.13.0-43-generic #72-Ubuntu SMP Mon Dec 8 19:35:06 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

编辑1:perror的输出

  1. mmap: Cannot allocate memory

添加了一行来打印errno

  1. printf("something is wrong: %d\n",errno);

输出是:

  1. something is wrong: 12

编辑2:来自/ proc / meminfo的巨大的tlb相关信息

  1. HugePages_Total: 0
  2. HugePages_Free: 0
  3. HugePages_Rsvd: 0
  4. HugePages_Surp: 0
  5. Hugepagesize: 2048 kB

解决方法

好吧,正如 Documentation/vm/hugetlspage.txt建议的那样
  1. echo 20 > /proc/sys/vm/nr_hugepages

解决了这个问题.在ubuntu 14.04上测试过.检查Why I can’t map memory with mmap.

猜你在找的C&C++相关文章