0

How can I use mmap to reserve memory within a virtual ramdisk? Lets say I do:

mkdir /mnt/ramdisk
mount -t tmpfs -o size=10m tmpfs /mnt/ramdisk

I now have a virtual ramdisk, but how do I map to it within my C program?

int main() {
    // ....
    addr = mmap(/* ramdisk address? */, size, PROT_READ_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
  • If you're using a RAMdisk then using `mmap` would just invoke overhead. Why not use `fopen`? – Dai Nov 21 '16 at 19:11
  • @Dai I'm using mmap as a way of reserving a region of memory for my library, but I am not sure how I would go about doing such a thing if I want to reserve this memory within a ramdisk instead of providing mmap the value of `NULL` for an address hint – Syntactic Fructose Nov 21 '16 at 19:13

1 Answers1

0

The fact that /mnt/ramdisk is a tmpfs doesn't have any bearing on how you use it.

If you wanted to memory-map a file on that device, you'd open() a file and map it with MAP_FILE (not MAP_ANONYMOUS) just as if it were a normal file. Don't pass an address; an appropriate one will be chosen for you.

  • But can I use that ramdisk for direct memory access? I can't simply call open() on a directory like `/mnt/ramdisk` – Syntactic Fructose Nov 21 '16 at 20:11
  • 1
    No. The semantics don't change just because it's a tmpfs -- it behaves exactly like any other filesystem. –  Nov 21 '16 at 20:20