1

I'm trying to open a file with mmap: It just works fine when using MAP_PRIVATE, but MAP_SHARED causes a invalid argument error: The file for mmap ist read/write

int size;
struct stat s;
const char * file_name = argv[1];
int fd = open (argv[1], O_RDWR);
int pagesize = sysconf(_SC_PAGE_SIZE);

/* Get the size of the file. */
int status = fstat (fd, & s);
size = s.st_size;
size += pagesize-(size%pagesize);

//mmap memory
d = mmap (0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
//error handeling
if(d == -1)
{
    perror("mmap");
    printf("Error opening file %s\n",argv[1]);
    return -1;
}

What am I doing wrong?

arnoapp
  • 2,416
  • 4
  • 38
  • 70
  • d is an unsigned char – arnoapp Dec 14 '13 at 02:04
  • 1
    @AzzUr1 Is there any difference if you do it the proper way: make `d` a pointer, e.g. `void *d;` and compare it to (void*)-1 ? `if (d == (void*)-1)`, if not, tell a bit more about your setup, e.g. which OS is this on, any compiler warnings you get, how you invoke the program and what output you get. And what specific `size` are you passing to mmap() ? (print it out for verification) – nos Dec 14 '13 at 02:07
  • You should definitely error check the `open()`, and you should probably error check the `fstat()` call. If either fails, you know you've got problems. Also, as already suggested, you should print out key values — such as `fd`, `pagesize`, `status`, `size`, even `argv[1]`. – Jonathan Leffler Dec 14 '13 at 02:53
  • 1
    the return check for mmap should be if(d==MAP_FAILED) or if(d==(VOID *)-1). As everyone else points out: check return codes. – jim mcnamara Dec 14 '13 at 02:57
  • According to strace everything works well except mmap which says invalid argument – arnoapp Dec 14 '13 at 11:25

1 Answers1

1

I found out that the cause for the error was that I was using Ubuntu Linux in a VM (Parallels) when running the code on my native system everything worked fine. Seems that Parallels doesn't implement this kind of memory modifications in it's filesystem drivers...

This question helped me a lot: Invalid argument for read-write mmap?

Community
  • 1
  • 1
arnoapp
  • 2,416
  • 4
  • 38
  • 70