简体   繁体   English

使用 mmap 读/写文件时如何解决 ENODEV

[英]How to resolve ENODEV when using mmap to read/write to a file

I'm trying to mmap a file for reading and writing, and currently I am receiving errcode 19: ENODEV.我正在尝试对文件进行 mmap 以进行读写,目前我收到 errcode 19: ENODEV。 I'm using a blank file with 2MB of space.我正在使用一个具有 2MB 空间的空白文件。

According to the man pages, this error occurs when the file is not compatible for mapping.根据手册页,当文件与映射不兼容时会发生此错误。 If this is true, I don't understand why;如果这是真的,我不明白为什么; It's just a regular empty file.它只是一个普通的空文件。 Additionally, it was provided by my professor, so presumably, it should work fine.此外,它是由我的教授提供的,所以想必它应该可以正常工作。 Is anything else going on?还有什么事吗?

Here is my code:这是我的代码:

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

int main(int argc, const char * argv[]) {
    int fd = open("Drive2MB", O_RDWR, S_IRUSR | S_IWUSR | S_IXUSR);
    if(fd < 0) {
        printf("open failure\n");
        exit(1);
    }

    char *drive = mmap(NULL, 1048576, PROT_WRITE, fd, MAP_SHARED, 0); 
    if(drive == MAP_FAILED) {
        printf("map failure\n");
        fprintf(stderr, "Value of errno: %d\n", errno);
        exit(1);
    }

    //test
    drive[513] = 'p';
    printf("%c", drive[513]);
}

If it is indeed the file, how would I go about creating a file that is compatible with mmap().如果确实是该文件,我将如何创建与 mmap() 兼容的文件。

Two mistakes:两个错误:

char *drive = mmap(NULL, 1048576, PROT_WRITE, fd, MAP_SHARED, 0); 

should be应该

char *drive = mmap(NULL, 1048576, PROT_WRITE, MAP_SHARED, fd, 0); 

and you can't map an empty file but only a file that has the length already.并且您不能映射一个空文件,而只能映射一个已经具有该长度的文件。

To populate Drive2MB do dd if=/dev/zero of=Drive2MB bs=1048576 count=1要填充Drive2MB请执行dd if=/dev/zero of=Drive2MB bs=1048576 count=1

MAP_SHARED happens to have the value of 1 so it tried to mmap stdout which is typically a terminal, which cannot be mapped. MAP_SHARED的值恰好为 1,因此它尝试映射mmap stdout ,它通常是无法映射的终端。

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

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