Skip to content

Commit 3840a3b

Browse files
committed
Fix windows WithDirLock to exclusive lock
We use LOCKFILE_FAIL_IMMEDIATELY, creating a shared lock that fail immediately if the lock cannot be acquired. This does not match the behavior of the unix version and does not make sense. Using now LOCKFILE_EXCLUSIVE_LOCK to acquire exclusive lock blocking until the lock can be acquired. Add constants for the flags and add comments for the argument names to prevent future errors. Signed-off-by: Nir Soffer <[email protected]>
1 parent e7dab76 commit 3840a3b

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

pkg/lockutil/lockutil_windows.go

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,20 +33,37 @@ var (
3333
procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
3434
)
3535

36+
const (
37+
// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
38+
LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
39+
LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
40+
)
41+
3642
func WithDirLock(dir string, fn func() error) error {
3743
dirFile, err := os.OpenFile(dir+".lock", os.O_CREATE, 0o644)
3844
if err != nil {
3945
return err
4046
}
4147
defer dirFile.Close()
42-
// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
43-
// 1 lock immediately
44-
if err := lockFileEx(syscall.Handle(dirFile.Fd()), 1, 0, 1, 0, &syscall.Overlapped{}); err != nil {
48+
if err := lockFileEx(
49+
syscall.Handle(dirFile.Fd()), // hFile
50+
LOCKFILE_EXCLUSIVE_LOCK, // dwFlags
51+
0, // dwReserved
52+
1, // nNumberOfBytesToLockLow
53+
0, // nNumberOfBytesToLockHigh
54+
&syscall.Overlapped{}, // lpOverlapped
55+
); err != nil {
4556
return fmt.Errorf("failed to lock %q: %w", dir, err)
4657
}
4758

4859
defer func() {
49-
if err := unlockFileEx(syscall.Handle(dirFile.Fd()), 0, 1, 0, &syscall.Overlapped{}); err != nil {
60+
if err := unlockFileEx(
61+
syscall.Handle(dirFile.Fd()), // hFile
62+
0, // dwReserved
63+
1, // nNumberOfBytesToLockLow
64+
0, // nNumberOfBytesToLockHigh
65+
&syscall.Overlapped{}, // lpOverlapped
66+
); err != nil {
5067
logrus.WithError(err).Errorf("failed to unlock %q", dir)
5168
}
5269
}()

0 commit comments

Comments
 (0)