Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release failed flock #43

Merged
merged 4 commits into from
Aug 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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