How does memory mapping work?

I can't find a guide or tutorial that explains it at all. Its there a better search term than Memory Mapping? What's the magic inbetween having the hard drive behave like the memory?

The best 'guide' is man mmap and some experimentation.

The "magic" is virtual memory. If you don't understand that yet, you'll need to. the paging game is a pretty good starter, I think.

How it works, hardware-wise, is the CPU keeps a big table of what addresses are assigned to what processes, and what real memory -- if any -- is assigned to that address. The OS can configure it on the fly. A page can be marked as 'unavailable', meaning, potentially valid but not yet read in or assigned actual memory. If a process accesses it, the CPU signals the OS which freezes that process. It checks and finds that the page isn't marked as 'ready' in the table, and that by its own (separate) records, ought to be a chunk of bigfile.txt. The OS finds an empty page, reads the right chunk into it, marks it belonging to the process, and wakes it up, which tries to read again and this time succeeds with no delay.

IOW, the CPU can mark memory in such a way as to freeze a process when it tries to use it. The OS is told when this happens, so it can do something to the memory, then revive it when ready, making a convincing illusion of the file existing in contiguous memory.

2 Likes

File Mapping - ????, ????! - CSDN??:wall:

Or this link?http://www.ifm-services.com/people/jamesk/papers/object_pascal/memorymapping.php

One of those refuses to load, and the other is in some odd computing language I've never seen before.

How about this?

To start you off:

char *mem;
int fd=open("filename", O_RDWR|O_CREAT, 0666); // Create the file
ftruncate(fd, getpagesize()); // Extend it to the length of the page size, probably 4K

// Map the file(MAP_SHARED) into memory with read and write permissions, at any available address(i.e. NULL)
mem=mmap(NULL, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0L);
if(mem == MAP_FAILED) // Failure doesnot mean null!
{
        perror("Couldn't mmap");
        return(1);
}

// Fill file with Z's
memset(mem, 'Z', getpagesize());
1 Like

Thank you Corona688 for the replies!:b:

Memory Mapped Files | Vladislav Online

Loading

Memory Mapped Files Abdelrahman Al-Ogail's Blog

UNIX Tips - Memory Management