aboutsummaryrefslogtreecommitdiffstats
path: root/util/system/flock.cpp
blob: fe88fecaff9cf970310c6771b610dc2455ac60bc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "flock.h"

#ifndef _unix_

    #include <util/generic/utility.h>

    #include "winint.h"
    #include <io.h>
    #include <errno.h>

    #ifdef __cplusplus
extern "C" {
    #endif

    int flock(int fd, int op) {
        return Flock((HANDLE)_get_osfhandle(fd), op);
    }

    int Flock(void* hdl, int op) {
        errno = 0;

        if (hdl == INVALID_HANDLE_VALUE) {
            errno = EBADF;
            return -1;
        }

        DWORD low = 1, high = 0;
        OVERLAPPED io;

        Zero(io);

        UnlockFileEx(hdl, 0, low, high, &io);

        switch (op & ~LOCK_NB) {
            case LOCK_EX:
            case LOCK_SH: {
                auto mode = ((op & ~LOCK_NB) == LOCK_EX) ? LOCKFILE_EXCLUSIVE_LOCK : 0;
                if (op & LOCK_NB) {
                    if (LockFileEx(hdl, mode | LOCKFILE_FAIL_IMMEDIATELY, 0, low, high, &io)) {
                        return 0;
                    } else if (GetLastError() == ERROR_LOCK_VIOLATION) {
                        ClearLastSystemError();
                        errno = EWOULDBLOCK;
                        return -1;
                    }
                } else {
                    if (LockFileEx(hdl, mode, 0, low, high, &io)) {
                        return 0;
                    }
                }
                break;
            }
            case LOCK_UN:
                return 0;
                break;
            default:
                break;
        }
        errno = EINVAL;
        return -1;
    }

    int fsync(int fd) {
        return _commit(fd);
    }

    #ifdef __cplusplus
}
    #endif

#endif