1

I want to map a file stored in ramdisk to a fixed address, but mmap fails. What mistake I am doing? Is there any other method to do this?

int fd =  open("/mnt/tmpfs/hello.txt",
                            (O_RDONLY),
                            (S_IRWXU | S_IRWXG | S_IRWXO) );
if ( fd < 0 )
     perror("open() error");

struct stat buf;
fstat(fd, &buf);
void * address = aligned_alloc(PGSIZE, buf.st_size)
void *new_address = mmap(address,
                      buf.st_size,
                      PROT_READ,
                      (MAP_SHARED|MAP_FIXED),
                      fd,
                      0);
if (new_address != address) {
    perror("mmap failed!")
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Cool Goose
  • 870
  • 10
  • 16
  • 1
    What is the value of errno? – PiRocks Oct 31 '21 at 04:21
  • 1
    Related: [When would one use mmap MAP_FIXED?](https://stackoverflow.com/a/28576674/68587) "Further, note that use of `MAP_FIXED` with a hard-coded address or a random address is **always a bug**. The only correct way to use `MAP_FIXED` is to replace an existing mapping whose address was assigned by a previous successful call to `mmap` without `MAP_FIXED`, or in some other way where you feel it's safe to replace whole pages." – John Kugelman Oct 31 '21 at 04:24
  • most likely, the problem is that `buf.st_size` is not a multiple of the page size. – Chris Dodd Oct 31 '21 at 07:40

0 Answers0