2011-03-24 30 views
4

根據下面的鏈接,我寫了一個小測試用例。但它不起作用。任何想法表示讚賞!scoped_lock在文件上不起作用?

參考: 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; 
} 
+0

定義「不起作用」。你有編譯器錯誤嗎?運行時斷言?意外的行爲?提供一些細節。 – ildjarn 2011-03-25 02:33:38

+0

它編譯,但在運行時,它不寫入fileLock.txt。 – echo 2011-03-25 03:26:55

+1

我可以用VC++ 2010 SP1和boost 1.46.1重現這一點。您應該將其發佈到boost用戶郵件列表中,因爲它似乎是一個錯誤,因爲文檔中的確切示例代碼無法工作。 – ildjarn 2011-03-25 07:12:33

回答

4

在Linux上運行的測試產生所需的輸出。我注意到這兩個警告:

您引用的頁面有這樣的警告:「如果使用std :: fstream/native文件句柄在該文件上使用文件鎖定時寫入文件,請不要關閉文件在釋放文件的所有鎖之前「。在Windows上使用LockFileExMSDN有這樣的說法:「如果鎖定過程第二次打開文件,則無法通過此第二個句柄訪問指定區域,直到解鎖該區域。」

看來,至少在Windows上,文件鎖定是每個句柄而不是每個文件。就我所知,這意味着你的程序在Windows下保證會失敗。

+0

感謝您的所有答案。我想我會在以後發佈它來提高用戶的郵件列表。如果您對此測試用例有新的想法,請發表評論。 – echo 2011-03-25 23:59:54

0

下面是一個解決方法,在基於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); 
}