ENODEV error in MMAP

2020-05-08 13:35发布

问题:

I'm trying to do a simple mapping of a new text file (given as a parameter) and I'm getting an ENODEV error in the mmap call. The fd is ok (no error in open call).

According to the documentation this error means "The underlying file system of the specified file does not support memory mapping." or from another source I found that it can mean that fd is a file descriptor for a special file (one that might be used for mapping either I/O or device memory). I don't understand why any of these reasons would be the case.

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>

#define SIZE1 10240

int main(int argc, char *argv[]){
    char *addr;
int fd;

mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

if(fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, mode) == -1){
    printf("error @ open\n");       
}

addr = (char*) mmap(NULL, SIZE1, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
...
munmap(addr, SIZE1);
return 0;
}

回答1:

This line is broken:

if(fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, mode) == -1){

You need to add parentheses around the assignment, because the comparison operator == has a higher precedence than the assignment operator =. Try this instead:

if ((fd = open(argv[1], O_CREAT | O_TRUNC, mode)) == -1) {



标签: c linux mmap