Dave F Dave F -4 years ago 215
C++ Question

What does boost interprocess file_lock actually do with the target file?

I've done some reading about

and it seems to do pretty much what I'm after (support shareable and exclusive locking, and being unlocked if the process crashes or exits).

One thing I'm not sure about though, is what does it do to the file? Can I use for example a file of 0 bytes long? Does
write anything into it? Or is its presence all the system cares about?

I've been using
now for some time to reliably memory map a file and write into it, now I need to go multiprocess and ensure that reads and writes to this file are protected;
does seem the way to go, I just wonder if I now need to add another file to use as a mutex.

Thanks in advance

Answer Source

what does it do to the file?

Boost does not do anything with the file, it relies on the operating system to get that job done. Support for memory mapped files is a generic capability of a demand-paged virtual memory operating system. Like Windows, Linux, OSX. Memory is normally backed by the paging file, having it backed by a specific file you select is but a small step. Boost just provides a platform-independent adapter, nothing more.

You'll want to take a look at the relevant OS documentation pages to see what's possible and how it is expected to work when you do something unusual. For Linux and OSX you'll want to look at the mmap man pages. For Windows look at CreatefileMapping.

file_lock does seem the way to go

Yes, you almost always need to arbitrate access to the memory mapped file so for example one process will only attempt to read the data when the other process finished writing it. The most suitable synchronization primitive for that is not a file_lock (the OS already locks the file), it is a named mutex. Use, say, boost's named_mutex class.

Do keep in mind that this is a very low-level interop mechanism and comes without any conveniences whatsoever. By the time you add all of the required synchronization, you're half-way to what the OS already does with a named pipe or local-loopback socket. If you discover that you have to copy data into the mapped view, not uncommon since it is not easily resizable, then you've lost all benefits.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download