Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2017-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <util/fs.h>7#include <util/check.h>8#include <util/syserror.h>10#include <cerrno>11#include <string>13#ifndef WIN3214#include <fcntl.h>15#include <unistd.h>16#else17#include <limits>18#include <windows.h>19#endif21namespace fsbridge {23FILE *fopen(const fs::path& p, const char *mode)24{25#ifndef WIN3226return ::fopen(p.c_str(), mode);27#else28return ::fopen(p.utf8string().c_str(), mode);29#endif30}32fs::path AbsPathJoin(const fs::path& base, const fs::path& path)33{34assert(base.is_absolute());35return path.empty() ? base : fs::path(base / path);36}38#ifndef WIN3240static std::string GetErrorReason()41{42return SysErrorString(errno);43}45FileLock::FileLock(const fs::path& file)46{47fd = open(file.c_str(), O_RDWR);48if (fd == -1) {49reason = GetErrorReason();50}51}53FileLock::~FileLock()54{55if (fd != -1) {56close(fd);57}58}60bool FileLock::TryLock()61{62if (fd == -1) {63return false;64}66struct flock lock;67lock.l_type = F_WRLCK;68lock.l_whence = SEEK_SET;69lock.l_start = 0;70lock.l_len = 0;71if (fcntl(fd, F_SETLK, &lock) == -1) {72reason = GetErrorReason();73return false;74}76return true;77}78#else80static std::string GetErrorReason() {81return Win32ErrorString(GetLastError());82}84FileLock::FileLock(const fs::path& file)85{86hFile = CreateFileW(file.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,87nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);88if (hFile == INVALID_HANDLE_VALUE) {89reason = GetErrorReason();90}91}93FileLock::~FileLock()94{95if (hFile != INVALID_HANDLE_VALUE) {96CloseHandle(hFile);97}98}100bool FileLock::TryLock()101{102if (hFile == INVALID_HANDLE_VALUE) {103return false;104}105_OVERLAPPED overlapped = {};106if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, std::numeric_limits<DWORD>::max(), std::numeric_limits<DWORD>::max(), &overlapped)) {107reason = GetErrorReason();108return false;109}110return true;111}112#endif114} // namespace fsbridge