开发者

scoped_lock doesn't work on file?

According to the link below, I wrote a small test case. But it doesn't work. Any idea is appreciated!

Reference: 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 <&开发者_运维问答lt; 10;
        file_out.flush();
        file_out.close();
    }

    return 0;
}


Running the test on Linux produces your desired output. I notice these two warnings:

The page you reference has this warning: "If you are using a std::fstream/native file handle to write to the file while using file locks on that file, don't close the file before releasing all the locks of the file."

Boost::file_lock apparently uses LockFileEx on Windows. MSDN has this to say: "If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region."

It seems like, on Windows at least, the file lock is per-handle, not per-file. As near as I can tell, that means that your program is guaranteed to fail under Windows.


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

The title of that bug is "interprocess::file_lock has incorrect behavior when win32 api is enabled".


Here is a workaround to append in a file with a file locking based on Boost 1.44.

#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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜