C 基本mmap(2)调用失败
我已经花了好几个小时来研究这段非常基本的代码,但我还没有理解为什么mmap2会失败C 基本mmap(2)调用失败,c,linux,mmap,C,Linux,Mmap,我已经花了好几个小时来研究这段非常基本的代码,但我还没有理解为什么mmap2会失败 #include <sys/mman.h> #include <sys/user.h> #include <err.h> #include <stdio.h> #include <stdlib.h> #define NPAGES 50 #define SLABSIZE (PAGE_SIZE * NPAGES) // 200 k
#include <sys/mman.h>
#include <sys/user.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#define NPAGES 50
#define SLABSIZE (PAGE_SIZE * NPAGES) // 200 kB
int
main(int argc, char *argv[])
{
char *slab;
printf("DEBUG: mmap(%#x, %u, %#x, %#x, %d, %u)\n",
NULL, SLABSIZE, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
slab = mmap(NULL, SLABSIZE, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
if (slab == MAP_FAILED)
err(1, "mmap");
}
我检查并重新检查了mmap2的手册页[1],似乎所有的要求都是可以的,但我肯定遗漏了什么。
我正在运行Linux内核4.8.13
谢谢。
-杰里米
[1] 在浏览您的程序时,我看到:
mmapNULL,204800,PROT_READ | PROT_WRITE,MAP_FILE | MAP_ANONYMOUS,-1,0=-1 EINVAL无效参数
您忘记了地图共享标志或地图专用标志。使用它可以是MAP_SHARED或MAP_PRIVATE,但您的程序需要其中一个:
slab = mmap(NULL, SLABSIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
引用手册页:
此行为通过在标志中仅包含以下值之一来确定:
重点是我的
因此,在你发毛之前的一般建议是:再次阅读文档;小睡一会儿;再看一次文档,想想你错过了什么
另一个提示是在一些或几个现有的可执行文件上使用。你会学到很多东西。当浏览你的程序时,我发现:
mmapNULL,204800,PROT_READ | PROT_WRITE,MAP_FILE | MAP_ANONYMOUS,-1,0=-1 EINVAL无效参数
您忘记了地图共享标志或地图专用标志。使用它可以是MAP_SHARED或MAP_PRIVATE,但您的程序需要其中一个:
slab = mmap(NULL, SLABSIZE, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
引用手册页:
此行为通过在标志中仅包含以下值之一来确定:
重点是我的
因此,在你发毛之前的一般建议是:再次阅读文档;小睡一会儿;再看一次文档,想想你错过了什么
另一个提示是在一些或几个现有的可执行文件上使用。你会学到很多。MAP\u ANON已被弃用。你想达到什么目标?如果您想将其映射到多个进程,请使用map_Shared,这两个进程都是正交的。MAP_ANONYMOUS只告诉您使用可交换内存备份该区域。MAP_SHARED表示此映射可以与其他进程共享。不推荐使用MAP_ANON。你想达到什么目标?如果您想将其映射到多个进程,请使用map_Shared,这两个进程都是正交的。MAP_ANONYMOUS只告诉您使用可交换内存备份该区域。MAP_SHARED表示此映射可以与其他进程共享。
MAP_SHARED
Share this mapping. Updates to the mapping are visible to
other processes mapping the same region, and (in the case of
file-backed mappings) are carried through to the underlying
file. (To precisely control when updates are carried through
to the underlying file requires the use of msync(2).)
MAP_PRIVATE
Create a private copy-on-write mapping. Updates to the
mapping are not visible to other processes mapping the same
file, and are not carried through to the underlying file. It
is unspecified whether changes made to the file after the
mmap() call are visible in the mapped region.