Fix WSL file locking by using flock instead of fcntl

Co-authored-by: sipa <pieter@wuille.net>
This commit is contained in:
Samuel Dobsonandsipa committed 2020-04-26 12:16:22 +12:00
1 parent 6ae99aab5d
commit e8fa0a3d20
1 file changed
+21
+21
View File
@@ -6,6 +6,9 @@
#ifndef WIN32 #ifndef WIN32
#include <fcntl.h> #include <fcntl.h>
#include <string>
#include <sys/file.h>
#include <sys/utsname.h>
#else #else
#ifndef NOMINMAX #ifndef NOMINMAX
#define NOMINMAX #define NOMINMAX
@@ -47,11 +50,27 @@ FileLock::~FileLock()
} }
} }
static bool IsWSL()
{
struct utsname uname_data;
return uname(&uname_data) == 0 && std::string(uname_data.version).find("Microsoft") != std::string::npos;
}
bool FileLock::TryLock() bool FileLock::TryLock()
{ {
if (fd == -1) { if (fd == -1) {
return false; return false;
} }
// Exclusive file locking is broken on WSL using fcntl (issue #18622)
// This workaround can be removed once the bug on WSL is fixed
static const bool is_wsl = IsWSL();
if (is_wsl) {
if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
reason = GetErrorReason();
return false;
}
} else {
struct flock lock; struct flock lock;
lock.l_type = F_WRLCK; lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET; lock.l_whence = SEEK_SET;
@@ -61,6 +80,8 @@ bool FileLock::TryLock()
reason = GetErrorReason(); reason = GetErrorReason();
return false; return false;
} }
}
return true; return true;
} }
#else #else