简体   繁体   English

为什么mmap在这里不起作用

[英]Why is mmap not working here

I get segmentation fault when I run the following piece of code... 运行以下代码时出现分段错误...

int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, 0, 0 );

x[0] = 42; // <--- Segmentation fault happens due to this

What is wrong here? 怎么了

You've specified the incorrect flags and file descriptor. 您指定了不正确的标志和文件描述符。 It looks like what you want is an anonymous (not backed by a file) mapping. 看起来您想要的是匿名(没有文件支持)映射。 If that's the case, the correct call would be: 如果是这样,正确的调用将是:

x = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);

You need to use the MAP_ANONYMOUS flag to tell Linux there is no file. 您需要使用MAP_ANONYMOUS标志来告诉Linux没有文件。 And you should pass -1 for the file descriptor, not 0. 并且您应该为文件描述符传递-1 ,而不是0。

OK, I got it. 好,我知道了。 I forgot to place MAP_ANONYMOUS , so it should had been like this... 我忘了放MAP_ANONYMOUS了 ,所以应该是这样的...

int * x = mmap( 0, 4096, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 
  0, 0 );

Its working this way. 它以这种方式工作。

man mmap says: man mmap说:

On success, mmap() returns a pointer to the mapped area. On error, the value MAP_FAILED (that is, (void *) -1) is returned, and errno is set appropriately

Check, whether x == MAP_FAILED or not. 检查x == MAP_FAILED是否x == MAP_FAILED May be this is the case. 可能是这种情况。

And you should always check that the result of mmap is not MAP_FAILED (that is, (void *) -1 ) and use errno to get the error code in that case. 而且,您应始终检查mmap的结果是否不是MAP_FAILED (即(void *) -1 ),并在这种情况下使用errno获取错误代码。

Your mmap could fail (eg because of resource limits set with setrlimit , or because the swap space is full). 您的mmap可能会失败(例如,由于使用setrlimit设置的资源限制或交换空间已满)。

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

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