Skip to content
This repository has been archived by the owner on Feb 24, 2020. It is now read-only.

Commit

Permalink
pkg/lock: Close the file descriptor on unsuccessful locking
Browse files Browse the repository at this point in the history
NewLock() opens a new file descriptor to lock on but if file
is already locked, Try*Lock() methods return error without closing
the corresponding file descriptor.
  • Loading branch information
shobhit85 committed Feb 24, 2017
1 parent f44c604 commit d772b35
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions pkg/lock/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func TryExclusiveLock(path string, lockType LockType) (*FileLock, error) {
}
err = l.TryExclusiveLock()
if err != nil {
l.Close()
return nil, err
}
return l, err
Expand All @@ -79,10 +80,12 @@ func (l *FileLock) ExclusiveLock() error {
// It will block if an exclusive lock is already held on the file/directory.
func ExclusiveLock(path string, lockType LockType) (*FileLock, error) {
l, err := NewLock(path, lockType)
if err == nil {
err = l.ExclusiveLock()
if err != nil {
return nil, err
}
err = l.ExclusiveLock()
if err != nil {
l.Close()
return nil, err
}
return l, nil
Expand All @@ -109,6 +112,7 @@ func TrySharedLock(path string, lockType LockType) (*FileLock, error) {
}
err = l.TrySharedLock()
if err != nil {
l.Close()
return nil, err
}
return l, nil
Expand All @@ -131,6 +135,7 @@ func SharedLock(path string, lockType LockType) (*FileLock, error) {
}
err = l.SharedLock()
if err != nil {
l.Close()
return nil, err
}
return l, nil
Expand Down Expand Up @@ -179,10 +184,12 @@ func NewLock(path string, lockType LockType) (*FileLock, error) {
var stat syscall.Stat_t
err = syscall.Fstat(lfd, &stat)
if err != nil {
l.Close()
return nil, err
}
// Check if the file is a regular file
if lockType == RegFile && !(stat.Mode&syscall.S_IFMT == syscall.S_IFREG) {
l.Close()
return nil, ErrNotRegular
}

Expand Down

0 comments on commit d772b35

Please sign in to comment.