boost文件鎖的使用


  boost中可以用boost::interprocess::file_lock類對文件進行加鎖和解鎖操作。

  

#include <fstream>
#include <iostream> 
#include <boost/interprocess/sync/file_lock.hpp> 
#include <cstdlib>

int main() 
{ 
  using namespace boost::interprocess; 
  std::string fileName("test"); 
  std::fstream file;

  file.open(fileName.c_str(), std::ios::out | std::ios::binary | 
      std::ios::trunc); 
  if (!file.is_open() || file.bad()) 
  {   
    std::cout << "Open failed" << std::endl; 
    exit(-1); 
  }
  std::cout << "Process 1 open file" << std::endl;

  try { 
    file_lock f_lock(fileName.c_str());
    f_lock.lock();
    std::cout << "Locked in Process 1" << std::endl;
    file.write("Process 1", 9); 
    file.flush(); 
    f_lock.unlock();
    std::cout << "Unlocked from Process 1" << std::endl;
  } catch (interprocess_exception& e) { 
    std::cout << e.what( ) << std::endl;
  }

  file.close();
  return 0;  
}

  為了避免作用域退出時,忘了解鎖引發錯誤,可使用boost::interprocess::lock_guard。

lock_guard<file_lock>  guard(lock);
{
  // ....    
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM