abroun abroun - 4 months ago 25
C Question

How good is the memory mapped Circular Buffer on Wikipedia?

I'm trying to implement a circular buffer in C, and have come across this example on Wikipedia (removed in July 2014). It looks as if it would provide a really nice interface for anyone reading from the buffer, as reads which wrap around from the end to the beginning of the buffer are handled automatically. So all reads are contiguous.

However, I'm a bit unsure about using it straight away as I don't really have much experience with memory mapping or virtual memory and I'm not sure that I fully understand what it's doing.

What I think I understand is that it's mapping a shared memory file the size of the buffer into memory twice. Then, whenever data is written into the buffer it appears in memory in 2 places at once. This allows all reads to be contiguous.

What would be really great is if someone with more experience of POSIX memory mapping could have a quick look at the code and tell me if the underlying mechanism used is really that efficient. Am I right in thinking for example that the file in /dev/shm used for the shared memory always stays in RAM or could it get written to the hard drive (performance hit) at some point? Are there any gotchas I should be aware of?

As it stands, I'm probably going to use a simpler method for my current project, but it'd be good to understand this to have it in my toolbox for the future.

Thanks in advance for your time.

ony ony
Answer

I think first anonymous mmap is done just to select some address area in non-used memory to hold both mappings.
"/dev/shm" is usually mounted with filesystem "tmpfs" which stores all the data in swap/memory. So actually it may result in writing to hard drive, but you have the same chances with your malloc-ed memory.

Even that my "/etc/fstab" says "glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for POSIX shared memory (shm_open, shm_unlink)." some systems may not follow that. But I hope that memory-mapped files works almost like swap, but they try to sync data to disk as soon as possible.

As man mkstemp states - glibc 2.06 and earlier creates file with permission 0666, that may lead into security hole if someone will catch your file between mkstemp and unlink.