diff --git a/filemutex.go b/filemutex.go new file mode 100644 index 0000000..a995523 --- /dev/null +++ b/filemutex.go @@ -0,0 +1,5 @@ +package filemutex + +import "errors" + +var AlreadyLocked = errors.New("lock already acquired") diff --git a/filemutex_flock.go b/filemutex_flock.go index 99a2726..e5f7742 100644 --- a/filemutex_flock.go +++ b/filemutex_flock.go @@ -35,8 +35,6 @@ func (m *FileMutex) Lock() error { return nil } -var AlreadyLocked = errors.New("lock already acquired") - func (m *FileMutex) TryLock() error { if err := syscall.Flock(m.fd, syscall.LOCK_EX|syscall.LOCK_NB); err != nil { if errno, ok := err.(syscall.Errno); ok { diff --git a/filemutex_windows.go b/filemutex_windows.go index 3eeb861..4691d51 100644 --- a/filemutex_windows.go +++ b/filemutex_windows.go @@ -16,7 +16,8 @@ var ( ) const ( - lockfileExclusiveLock = 2 + lockfileFailImmediately = 1 + lockfileExclusiveLock = 2 ) func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { @@ -58,6 +59,19 @@ func New(filename string) (*FileMutex, error) { return &FileMutex{fd: fd}, nil } +func (m *FileMutex) TryLock() error { + var ol syscall.Overlapped + if err := lockFileEx(m.fd, lockfileFailImmediately|lockfileExclusiveLock, 0, 1, 0, &ol); err != nil { + if errno, ok := err.(syscall.Errno); ok { + if errno == syscall.Errno(0x21) { + return AlreadyLocked + } + } + return err + } + return nil +} + func (m *FileMutex) Lock() error { var ol syscall.Overlapped if err := lockFileEx(m.fd, lockfileExclusiveLock, 0, 1, 0, &ol); err != nil {