master
h 53 lines 1.47 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 #ifndef NETDATA_FILE_LOCK_H
4 #define NETDATA_FILE_LOCK_H
5
6 #include "libnetdata/libnetdata-platform-fwd.h"
7
8 #if defined(OS_WINDOWS)
9 #include <windows.h>
10 #endif
11
12 typedef struct file_lock {
13 #if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_MACOS)
14 int fd;
15 #elif defined(OS_WINDOWS)
16 HANDLE handle;
17 #else
18 #error "Unsupported operating system"
19 #endif
20 } FILE_LOCK;
21
22 // Initialize to invalid values
23 #if defined(OS_LINUX) || defined(OS_FREEBSD) || defined(OS_MACOS)
24 #define FILE_LOCK_INVALID ((FILE_LOCK){ .fd = -1 })
25 #define FILE_LOCK_OK(lock) ((lock).fd != -1)
26 #elif defined(OS_WINDOWS)
27 #define FILE_LOCK_INVALID ((FILE_LOCK){ .handle = INVALID_HANDLE_VALUE })
28 #define FILE_LOCK_OK(lock) ((lock).handle != INVALID_HANDLE_VALUE)
29 #endif
30
31 /**
32 * Get a file lock
33 *
34 * Attempts to acquire an exclusive lock on a file. The lock is automatically released
35 * when the process exits or if the process crashes. Only one process can hold the lock
36 * at a time.
37 *
38 * @param filename UTF-8 encoded filename (MSYS2/Cygwin path format or native Windows path on Windows)
39 * @return FILE_LOCK The lock handle. Use FILE_LOCK_OK() to check if lock was acquired
40 */
41 FILE_LOCK file_lock_get(const char *filename);
42
43 /**
44 * Release a file lock
45 *
46 * Releases a previously acquired file lock. After calling this function,
47 * another process may acquire the lock.
48 *
49 * @param lock The lock to release
50 */
51 void file_lock_release(FILE_LOCK lock);
52
53 #endif //NETDATA_FILE_LOCK_H