Add lock file

This commit is contained in:
Timofey 2022-08-10 21:49:37 +03:00
parent c2d0033f78
commit 4aa3194e00
2 changed files with 37 additions and 0 deletions

18
src/utils/lock_file.cpp Normal file
View file

@ -0,0 +1,18 @@
#include <utils/lock_file.hpp>
#include <unistd.h>
#include <sys/file.h>
namespace utils::filesystem {
void LockFile::Lock() {
fd_ = open(path_.data(), O_RDWR | O_CREAT, 0666);
while (flock(fd_, LOCK_EX) != 0) {
}
}
void LockFile::Unlock() {
while (flock(fd_, LOCK_UN) != 0) {
}
close(fd_);
}
} // namespace utils::filesystem

19
src/utils/lock_file.hpp Normal file
View file

@ -0,0 +1,19 @@
#pragma once
#include <string>
namespace utils::filesystem {
class LockFile {
public:
LockFile(std::string path) : path_(std::move(path) + ".lock") {}
void Lock();
void lock() { Lock(); }
void Unlock();
void unlock() { Unlock(); }
private:
std::string path_;
int fd_ = -1;
};
} // namespace utils::filesystem