2026-01-16 22:45:06 -05:00
|
|
|
#ifndef AXIO_CFILELOCK_H
|
|
|
|
|
#define AXIO_CFILELOCK_H
|
2018-12-08 23:44:41 -07:00
|
|
|
|
|
|
|
|
#include <cstdio>
|
|
|
|
|
#include "Common/TString.h"
|
|
|
|
|
|
2019-05-24 23:36:03 -10:00
|
|
|
#ifndef _WIN32
|
|
|
|
|
#include <sys/file.h>
|
|
|
|
|
#include <unistd.h>
|
|
|
|
|
#endif
|
|
|
|
|
|
2018-12-08 23:44:41 -07:00
|
|
|
// Maintain a file handle to prevent other processes from accessing the file.
|
|
|
|
|
class CFileLock
|
|
|
|
|
{
|
2019-05-24 23:36:03 -10:00
|
|
|
#ifdef _WIN32
|
|
|
|
|
FILE* mpFile = nullptr;
|
|
|
|
|
#else
|
|
|
|
|
int mpFile = -1;
|
|
|
|
|
#endif
|
2018-12-08 23:44:41 -07:00
|
|
|
|
|
|
|
|
public:
|
2019-05-24 23:36:03 -10:00
|
|
|
CFileLock() = default;
|
2018-12-08 23:44:41 -07:00
|
|
|
|
|
|
|
|
~CFileLock()
|
|
|
|
|
{
|
|
|
|
|
Release();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void Lock(const TString& rkPath)
|
|
|
|
|
{
|
|
|
|
|
Release();
|
2019-05-24 23:36:03 -10:00
|
|
|
#ifdef _WIN32
|
2018-12-23 21:44:02 -07:00
|
|
|
mpFile = _wfopen(ToWChar(rkPath), L"a+");
|
2019-05-24 23:36:03 -10:00
|
|
|
#else
|
2019-11-19 05:05:22 +00:00
|
|
|
mpFile = open(*rkPath, O_CREAT | O_APPEND | O_RDWR, 0644);
|
2019-05-24 23:36:03 -10:00
|
|
|
flock(mpFile, LOCK_EX);
|
|
|
|
|
#endif
|
2018-12-08 23:44:41 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void Release()
|
|
|
|
|
{
|
2019-05-24 23:36:03 -10:00
|
|
|
#ifdef _WIN32
|
2018-12-08 23:44:41 -07:00
|
|
|
if (mpFile)
|
|
|
|
|
fclose(mpFile);
|
2019-05-24 23:36:03 -10:00
|
|
|
#else
|
|
|
|
|
if (mpFile != -1)
|
|
|
|
|
close(mpFile);
|
|
|
|
|
#endif
|
2018-12-08 23:44:41 -07:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2026-01-16 22:45:06 -05:00
|
|
|
#endif // AXIO_CFILELOCK_H
|