Reputation: 63
I'm trying to mmap a file for reading and writing, and currently I am receiving errcode 19: ENODEV. I'm using a blank file with 2MB of space.
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().
Upvotes: 2
Views: 1717
Reputation: 43327
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
MAP_SHARED
happens to have the value of 1 so it tried to mmap stdout
which is typically a terminal, which cannot be mapped.
Upvotes: 1