文件夹锁,防止一个应用多开的情况下访问共同文件夹

一个应用开两次,第二个将被阻塞直到第一个退出

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值