Skip to content

Commit

Permalink
Make windows filelocking exclusive
Browse files Browse the repository at this point in the history
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
  • Loading branch information
apostasie committed Aug 9, 2024
1 parent 1d9d22c commit 5cb524a
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions pkg/lockutil/lockutil_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ func WithDirLock(dir string, fn func() error) error {
}
defer dirFile.Close()
// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
// 1 lock immediately
if err = windows.LockFileEx(windows.Handle(dirFile.Fd()), 1, 0, 1, 0, &windows.Overlapped{}); err != nil {
if err = windows.LockFileEx(windows.Handle(dirFile.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, ^uint32(0), ^uint32(0), &windows.Overlapped{}); err != nil {
return fmt.Errorf("failed to lock %q: %w", dir, err)
}

defer func() {
if err := windows.UnlockFileEx(windows.Handle(dirFile.Fd()), 0, 1, 0, &windows.Overlapped{}); err != nil {
if err := windows.UnlockFileEx(windows.Handle(dirFile.Fd()), 0, ^uint32(0), ^uint32(0), &windows.Overlapped{}); err != nil {
log.L.WithError(err).Errorf("failed to unlock %q", dir)
}
}()
Expand All @@ -50,8 +49,7 @@ func Lock(dir string) (*os.File, error) {
return nil, err
}
// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
// 1 lock immediately
if err = windows.LockFileEx(windows.Handle(dirFile.Fd()), 1, 0, 1, 0, &windows.Overlapped{}); err != nil {
if err = windows.LockFileEx(windows.Handle(dirFile.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, ^uint32(0), ^uint32(0), new(windows.Overlapped)); err != nil {
return nil, fmt.Errorf("failed to lock %q: %w", dir, err)
}
return dirFile, nil
Expand All @@ -62,5 +60,5 @@ func Unlock(locked *os.File) error {
_ = locked.Close()
}()

return windows.UnlockFileEx(windows.Handle(locked.Fd()), 0, 1, 0, &windows.Overlapped{})
return windows.UnlockFileEx(windows.Handle(locked.Fd()), 0, ^uint32(0), ^uint32(0), &windows.Overlapped{})
}

0 comments on commit 5cb524a

Please sign in to comment.