lock_windows.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // +build windows
  2. package providers
  3. import (
  4. "syscall"
  5. "unsafe"
  6. )
  7. var (
  8. modkernel32 = syscall.NewLazyDLL("kernel32.dll")
  9. procLockFileEx = modkernel32.NewProc("LockFileEx")
  10. procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
  11. )
  12. const (
  13. // LOCKFILE_EXCLUSIVE_LOCK - request exclusive lock
  14. lockfileExclusiveLock = 0x00000002
  15. )
  16. // lockFile acquires an exclusive lock on the file using Windows LockFileEx
  17. func lockFile(fd int) error {
  18. // LockFileEx parameters:
  19. // - hFile: file handle
  20. // - dwFlags: LOCKFILE_EXCLUSIVE_LOCK for exclusive lock
  21. // - dwReserved: must be 0
  22. // - nNumberOfBytesToLockLow: low-order 32 bits of lock range (1 byte is enough)
  23. // - nNumberOfBytesToLockHigh: high-order 32 bits of lock range
  24. // - lpOverlapped: pointer to OVERLAPPED structure
  25. var overlapped syscall.Overlapped
  26. r1, _, err := procLockFileEx.Call(
  27. uintptr(fd),
  28. uintptr(lockfileExclusiveLock),
  29. 0,
  30. 1,
  31. 0,
  32. uintptr(unsafe.Pointer(&overlapped)),
  33. )
  34. if r1 == 0 {
  35. return err
  36. }
  37. return nil
  38. }
  39. // unlockFile releases the lock on the file using Windows UnlockFileEx
  40. func unlockFile(fd int) error {
  41. var overlapped syscall.Overlapped
  42. r1, _, err := procUnlockFileEx.Call(
  43. uintptr(fd),
  44. 0,
  45. 1,
  46. 0,
  47. uintptr(unsafe.Pointer(&overlapped)),
  48. )
  49. if r1 == 0 {
  50. return err
  51. }
  52. return nil
  53. }