简体   繁体   English

mmap无效参数错误

[英]mmap invalid argument error

This is the first time I use mmap system call. 这是我第一次使用mmap系统调用。 I am getting invalid argument error and I do not understand why , obviously I missing something Please help me, thank you 我收到了无效的参数错误,但我不明白为什么,显然我缺少了一些东西,请帮帮我,谢谢

#include <stdio.h>
#include <sys/mman.h>


int main() {

    long pageSize = getpagesize () ; 

    size_t length = 4096 ;


    int * map = (int * ) mmap ( 0 , length , PROT_READ | PROT_WRITE , MAP_ANONYMOUS , 0 , 0 ) ; 
        if ( map == MAP_FAILED ) {

            perror ( " error mapping " ) ;

        }

    return 0 ;
}

You need to specify at least one of MAP_PRIVATE or MAP_SHARED in the flags. 您需要在标志中至少指定MAP_PRIVATEMAP_SHARED之一。 Also, as the other answer says, you should have -1 as the file descriptor for portability, but that's not where your problem is (since you tagged this question with linux and linux ignores the file descriptor for anon mappings). 另外,正如另一个答案所说,您应该将-1作为可移植性的文件描述符,但这不是您的问题所在(因为您使用linux标记了这个问题,而linux忽略了匿名映射的文件描述符)。

You are passing 0 as the file descriptor. 您正在传递0作为文件描述符。 Anonymous mappings should always use -1 as the file descriptor, since they are not backed by a file. 匿名映射应始终使用-1作为文件描述符,因为它们没有文件支持。 Also, as the other answer says, MAP_ANONYMOUS should be complemented by either MAP_PRIVATE or MAP_SHARED . 另外,正如另一个答案所说, MAP_ANONYMOUS应该由MAP_PRIVATEMAP_SHARED来补充。

The correct way to call it would be: 正确的调用方式是:

int *map = mmap(0, length, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);

Note that the cast is not necessary since mmap returns void * . 注意,因为mmap返回void *所以不需要mmap

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

int *map = mmap(0, length, PROT_READ|PROT_WRITE, MAP PRIVATE|MAP_ANONYMOUS, -1, 0);

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

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

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