forked from OpenPrinting/ipp-usb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flock_windows.go
87 lines (71 loc) · 1.34 KB
/
flock_windows.go
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* ipp-usb - HTTP reverse proxy, backed by IPP-over-USB connection to device
*
* Copyright (C) 2020 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* File locking -- Windows version
*/
package main
/*
#define NTDDI_VERSION NTDDI_WIN7
#include <fileapi.h>
#include <windows.h>
*/
import "C"
import (
"os"
"runtime"
"syscall"
)
// FileLock acquires file lock
func FileLock(file *os.File, exclusive, wait bool) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var flags C.DWORD
if exclusive {
flags |= C.LOCKFILE_EXCLUSIVE_LOCK
}
if !wait {
flags |= C.LOCKFILE_FAIL_IMMEDIATELY
}
var ovp C.OVERLAPPED
ok := C.LockFileEx(
C.HANDLE(file.Fd()),
flags,
0,
0xffffffff,
0xffffffff,
&ovp,
)
if int(ok) != 0 {
return nil
}
switch errno := C.GetLastError(); errno {
case C.NO_ERROR, C.ERROR_LOCK_VIOLATION:
return ErrLockIsBusy
default:
return syscall.Errno(errno)
}
}
// FileUnlock releases file lock
func FileUnlock(file *os.File) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var ovp C.OVERLAPPED
ok := C.UnlockFileEx(
C.HANDLE(file.Fd()),
0,
0xffffffff,
0xffffffff,
&ovp,
)
if int(ok) != 0 {
return nil
}
switch errno := C.GetLastError(); errno {
case C.NO_ERROR:
return nil
default:
return syscall.Errno(errno)
}
}