Friday, June 20, 2008

Memory Mapped Files

I've only recently learned about memory-mapped files in Linux. Until recently, to perform file I/O, I followed the textbook examples of using read and write calls on file descriptors or streams. It wasn't until I browsed the git source (to help with my git clone) that I came across a mysterious mmap() call.

Not only is it more efficient for the reasons given in the Wikipedia article, but it is easier to work with file contents as if they were already in memory. There's no need to learn the syntax and semantics of various read and write calls.

The only tough part is remembering the mmap syntax. But the call can be readily encapsulated. For example, to read a file, I define a function like the following:
void *map_file_to_memory(size_t *len, const char *path) {
int fd = open_or_die(path, O_RDONLY);
*len = get_size_of(fd);
if (!*len) {
return NULL;
void *map = mmap(NULL, *len, PROT_READ, MAP_PRIVATE, fd, 0);
if (MAP_FAILED == map) die("mmap failed");
return map;
There are concerns with large files, but hopefully madvise() is well-written and can prevent excessive page faults.


malathi reddy said...

Rummy game is familiar in all of the countries, Mostly people play it because it's an ancient game since long back rummy has been originated.It's a game of probability which required skill as well luck.The best way to expertise in the rummy game is to play the online rummy game.I found an awesome site which offers free chips which can also play real cash games.

bilal khan said...

it's incredibly decent and meanful. it's enormously cool blog. Partner is incredibly noteworthy have truly helped heaps of individuals who visit blog and give them usefull data.

Self Assessment Return for Self Employed

Pranav Kumar said...

Thanks for the blog. What is the difference between Thai Rummy and 13 cards rummy .

srithar said...

Which is your favourite Rummy Game ?If you like 13 cards rummy visit RUMMY Adda where you can claim Rs 50 as free signup bonus.