diff options
author | Samuel Dobson <dobsonsa68@gmail.com> | 2020-04-19 11:07:14 +1200 |
---|---|---|
committer | fanquake <fanquake@gmail.com> | 2020-06-09 21:09:22 +0800 |
commit | febebc4ea68104bba9ad2cf4468fc50e6136f803 (patch) | |
tree | 35865c1c899c6980c1fb3403210799610d313844 /src/fs.cpp | |
parent | 5c7151a60468bf3c603ffe0490fbbe95736fdd69 (diff) | |
download | bitcoin-febebc4ea68104bba9ad2cf4468fc50e6136f803.tar.xz |
Fix WSL file locking by using flock instead of fcntl
Co-authored-by: sipa <pieter@wuille.net>
Github-Pull: #18700
Rebased-From: e8fa0a3d2025509fcddc59fc618e91371542cf87
Diffstat (limited to 'src/fs.cpp')
-rw-r--r-- | src/fs.cpp | 37 |
1 files changed, 29 insertions, 8 deletions
diff --git a/src/fs.cpp b/src/fs.cpp index 066c6c10d3..e68c97b3ca 100644 --- a/src/fs.cpp +++ b/src/fs.cpp @@ -6,6 +6,9 @@ #ifndef WIN32 #include <fcntl.h> +#include <string> +#include <sys/file.h> +#include <sys/utsname.h> #else #ifndef NOMINMAX #define NOMINMAX @@ -47,20 +50,38 @@ 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() { if (fd == -1) { return false; } - struct flock lock; - lock.l_type = F_WRLCK; - lock.l_whence = SEEK_SET; - lock.l_start = 0; - lock.l_len = 0; - if (fcntl(fd, F_SETLK, &lock) == -1) { - reason = GetErrorReason(); - 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; + lock.l_type = F_WRLCK; + lock.l_whence = SEEK_SET; + lock.l_start = 0; + lock.l_len = 0; + if (fcntl(fd, F_SETLK, &lock) == -1) { + reason = GetErrorReason(); + return false; + } } + return true; } #else |