Scoped_lock not working in file?

According to the link below, I wrote a small test case. But that will not work. Any idea appreciated!

Link: http://www.cppprog.com/boost_doc/doc/html/interprocess/synchronization_mechanisms.html#interprocess.synchronization_mechanisms.file_lock.file_lock_careful_iostream

#include <iostream> #include <fstream> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> using namespace std; using namespace boost::interprocess; int main() { ofstream file_out("fileLock.txt"); file_lock f_lock("fileLock.txt"); { scoped_lock<file_lock> e_lock(f_lock); // it works if I comment this out file_out << 10; file_out.flush(); file_out.close(); } return 0; } 
+4
source share
3 answers

Running a test on Linux gives the desired result. I notice these two warnings:

The page you're linking to has this warning: "If you use the std :: fstream / native file descriptor to write to a file when using file locks in this file, do not close the file before you release all file locks."

Boost::file_lock obviously uses LockFileEx on Windows. MSDN says the following: "If the lock process opens the file a second time, it cannot access the specified area through this second descriptor until it unlocks the region."

It seems that on Windows at least a file lock is for each descriptor, not for the file. As far as I can tell, this means that your program will fail under Windows.

+4
source

Your code seems susceptible to this long-standing bug on the boost site: https://svn.boost.org/trac/boost/ticket/2796

The header of this error is " interprocess :: file_lock has incorrect behavior when win32 api is enabled .

+3
source

The following is a workaround for adding files based on Boost 1.44 to a file with blocking.

 #include "boost/format.hpp" #include "boost/interprocess/detail/os_file_functions.hpp" namespace ip = boost::interprocess; namespace ipc = boost::interprocess::detail; void fileLocking_withHandle() { static const string filename = "fileLocking_withHandle.txt"; // Get file handle boost::interprocess::file_handle_t pFile = ipc::create_or_open_file(filename.c_str(), ip::read_write); if ((pFile == 0 || pFile == ipc::invalid_file())) { throw runtime_error(boost::str(boost::format("File Writer fail to open output file: %1%") % filename).c_str()); } // Lock file ipc::acquire_file_lock(pFile); // Move writing pointer to the end of the file ipc::set_file_pointer(pFile, 0, ip::file_end); // Write in file ipc::write_file(pFile, (const void*)("bla"), 3); // Unlock file ipc::release_file_lock(pFile); // Close file ipc::close_file(pFile); } 
0
source

Source: https://habr.com/ru/post/1345152/


All Articles