一个应用开两次,第二个将被阻塞直到第一个退出
#include <mutex>
#include <thread>
#include <string>
#include <map>
#include <boost\filesystem.hpp>
#include <boost\interprocess\sync\file_lock.hpp>
template <typename T, typename... Args>
std::unique_ptr<T> MakeUnique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
typedef boost::interprocess::file_lock File_Lock;
std::map<std::string, std::unique_ptr<File_Lock>> dir_locks;
std::mutex cs_dir_locks;
namespace fs = boost::filesystem;
bool LockDirectory(const fs::path& directory, const std::string lockfile_name, bool probe_only)
{
std::lock_guard<std::mutex> ulock(cs_dir_locks);
fs::path pathLockFile = directory / lockfile_name;
// 防止被锁后再次被锁
if (dir_locks.count(pathLockFile.string())) {
printf("directory had been locked");
return true;
}
//如果没有锁文件,创建一个空的文件作为锁文件
FILE* file;
fopen_s(&file, pathLockFile.string().c_str(), "a");
if (file) fclose(file);
try {
auto lock = MakeUnique<File_Lock>(pathLockFile.string().c_str());
if (!lock->try_lock()) {
return false;
}
if (!probe_only) {
// 将锁加入到map中
dir_locks.emplace(pathLockFile.string(), std::move(lock));
}
}
catch (const boost::interprocess::interprocess_exception& e) {
printf("Error while attempting to lock directory %s: %s", directory.string(), e.what());
return false;
}
return true;
}
int main()
{
//锁文件夹
fs::path dir("F:\\");
std::string lock_name = ".lock";
LockDirectory(dir, lock_name,false);
阻止子线程访问
std::thread t1(LockDirectory, dir, lock_name, false);
t1.join();
//文件锁
boost::filesystem::path file_name = dir / "test.txt";
File_Lock f_lock(file_name.string().c_str());
std::lock_guard<File_Lock> guard(f_lock);
system("pause");
return 0;
}