Skip to content

Commit

Permalink
Merge pull request #43 from azr/release_failed_flock
Browse files Browse the repository at this point in the history
Release failed flock
  • Loading branch information
theckman committed Aug 22, 2020
2 parents 5135e61 + 0eda267 commit 8a39eb4
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions flock.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,11 @@ func (f *Flock) setFh() error {
f.fh = fh
return nil
}

// ensure the file handle is closed if no lock is held
func (f *Flock) ensureFhState() {
if !f.l && !f.r && f.fh != nil {
f.fh.Close()
f.fh = nil
}
}
30 changes: 30 additions & 0 deletions flock_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package flock

import (
"io/ioutil"
"os"
"testing"
)

func Test(t *testing.T) {
tmpFileFh, err := ioutil.TempFile(os.TempDir(), "go-flock-")
tmpFileFh.Close()
tmpFile := tmpFileFh.Name()
os.Remove(tmpFile)

lock := New(tmpFile)
locked, err := lock.TryLock()
if locked == false || err != nil {
t.Fatalf("failed to lock: locked: %t, err: %v", locked, err)
}

newLock := New(tmpFile)
locked, err = newLock.TryLock()
if locked != false || err != nil {
t.Fatalf("should have failed locking: locked: %t, err: %v", locked, err)
}

if newLock.fh != nil {
t.Fatal("file handle should have been released and be nil")
}
}
2 changes: 2 additions & 0 deletions flock_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func (f *Flock) lock(locked *bool, flag int) error {
if err := f.setFh(); err != nil {
return err
}
defer f.ensureFhState()
}

if err := syscall.Flock(int(f.fh.Fd()), flag); err != nil {
Expand Down Expand Up @@ -142,6 +143,7 @@ func (f *Flock) try(locked *bool, flag int) (bool, error) {
if err := f.setFh(); err != nil {
return false, err
}
defer f.ensureFhState()
}

var retried bool
Expand Down
2 changes: 2 additions & 0 deletions flock_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func (f *Flock) lock(locked *bool, flag uint32) error {
if err := f.setFh(); err != nil {
return err
}
defer f.ensureFhState()
}

if _, errNo := lockFileEx(syscall.Handle(f.fh.Fd()), flag, 0, 1, 0, &syscall.Overlapped{}); errNo > 0 {
Expand Down Expand Up @@ -122,6 +123,7 @@ func (f *Flock) try(locked *bool, flag uint32) (bool, error) {
if err := f.setFh(); err != nil {
return false, err
}
defer f.ensureFhState()
}

_, errNo := lockFileEx(syscall.Handle(f.fh.Fd()), flag|winLockfileFailImmediately, 0, 1, 0, &syscall.Overlapped{})
Expand Down

0 comments on commit 8a39eb4

Please sign in to comment.