Files

53 lines
856 B
C++
Raw Permalink Normal View History

2026-01-16 22:45:06 -05:00
#ifndef AXIO_CFILELOCK_H
#define AXIO_CFILELOCK_H
#include <cstdio>
#include "Common/TString.h"
2019-05-24 23:36:03 -10:00
#ifndef _WIN32
#include <sys/file.h>
#include <unistd.h>
#endif
// 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
public:
2019-05-24 23:36:03 -10:00
CFileLock() = default;
~CFileLock()
{
Release();
}
void Lock(const TString& rkPath)
{
Release();
2019-05-24 23:36:03 -10:00
#ifdef _WIN32
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
}
void Release()
{
2019-05-24 23:36:03 -10:00
#ifdef _WIN32
if (mpFile)
fclose(mpFile);
2019-05-24 23:36:03 -10:00
#else
if (mpFile != -1)
close(mpFile);
#endif
}
};
2026-01-16 22:45:06 -05:00
#endif // AXIO_CFILELOCK_H