Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
flock.hpp
Go to the documentation of this file.
1#pragma once
2
3#ifdef _WIN32
4#include <io.h>
5#include <windows.h>
6#define LOCK_SH 1
7#define LOCK_EX 2
8#define LOCK_NB 4
9#define LOCK_UN 8
10
11static inline int flock(int fd, int operation)
12{
13 HANDLE h = (HANDLE)_get_osfhandle(fd);
14 OVERLAPPED o = { 0 };
15 DWORD flags = 0;
16
17 if (operation & LOCK_NB)
18 flags |= LOCKFILE_FAIL_IMMEDIATELY;
19 if (operation & LOCK_EX)
20 flags |= LOCKFILE_EXCLUSIVE_LOCK;
21
22 if (operation & LOCK_UN) {
23 return UnlockFileEx(h, 0, MAXDWORD, MAXDWORD, &o) ? 0 : -1;
24 }
25 return LockFileEx(h, flags, 0, MAXDWORD, MAXDWORD, &o) ? 0 : -1;
26}
27#else
28#include <sys/file.h>
29#endif
30
31#include <fcntl.h>
32#include <string_view>
33#include <unistd.h>
34
36 int fd;
37
38 explicit FileLockGuard([[maybe_unused]] std::string_view path,
39 [[maybe_unused]] int flags = O_RDWR | O_CREAT,
40 [[maybe_unused]] mode_t mode = 0644)
41 {
42#ifndef __wasm__
43 fd = open(std::string(path).c_str(), flags, mode);
44 if (fd != -1) {
45 flock(fd, LOCK_EX);
46 }
47#else
48 fd = -1;
49#endif
50 }
51
53 {
54#ifndef __wasm__
55 if (fd != -1) {
56 flock(fd, LOCK_UN);
57 close(fd);
58 }
59#endif
60 }
61
62 FileLockGuard(const FileLockGuard&) = delete;
64};
FileLockGuard(std::string_view path, int flags=O_RDWR|O_CREAT, mode_t mode=0644)
Definition flock.hpp:38
FileLockGuard & operator=(const FileLockGuard &)=delete
FileLockGuard(const FileLockGuard &)=delete