FileSystem: Fix POSIXLock positioning

This commit is contained in:
Stenzek 2023-01-30 18:00:16 +10:00
parent c6a57273d1
commit 9dbe44ca3e
1 changed files with 29 additions and 17 deletions

View File

@ -1917,36 +1917,48 @@ bool FileSystem::SetPathCompression(const char* path, bool enable)
return false; return false;
} }
FileSystem::POSIXLock::POSIXLock(int fd) static bool SetLock(int fd, bool lock)
{ {
if (lockf(fd, F_LOCK, 0) == 0) // We want to lock the whole file.
const off_t offs = lseek(fd, 0, SEEK_CUR);
if (offs < 0)
{ {
m_fd = fd; Log_ErrorPrintf("lseek(%d) failed: %d", fd, errno);
} return false;
else
{
Log_ErrorPrintf("lockf() failed: %d", errno);
m_fd = -1;
}
} }
FileSystem::POSIXLock::POSIXLock(std::FILE* fp) if (offs != 0 && lseek(fd, 0, SEEK_SET) < 0)
{ {
m_fd = fileno(fp); Log_ErrorPrintf("lseek(%d, 0) failed: %d", fd, errno);
if (m_fd >= 0) return false;
}
const bool res = (lockf(fd, lock ? F_LOCK : F_ULOCK, 0) == 0);
if (lseek(fd, offs, SEEK_SET) < 0)
Panic("Repositioning file descriptor after lock failed.");
if (!res)
Log_ErrorPrintf("lockf() for %s failed: %d", lock ? "lock" : "unlock", errno);
return res;
}
FileSystem::POSIXLock::POSIXLock(int fd) : m_fd(fd)
{ {
if (lockf(m_fd, F_LOCK, 0) != 0) if (!SetLock(m_fd, true))
{
Log_ErrorPrintf("lockf() failed: %d", errno);
m_fd = -1; m_fd = -1;
} }
}
FileSystem::POSIXLock::POSIXLock(std::FILE* fp) : m_fd(fileno(fp))
{
if (!SetLock(m_fd, true))
m_fd = -1;
} }
FileSystem::POSIXLock::~POSIXLock() FileSystem::POSIXLock::~POSIXLock()
{ {
if (m_fd >= 0) if (m_fd >= 0)
lockf(m_fd, F_ULOCK, m_fd); SetLock(m_fd, false);
} }
#endif #endif