lock_unix.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build !windows,!plan9,!solaris
  15. package fileutil
  16. import (
  17. "errors"
  18. "os"
  19. "syscall"
  20. )
  21. var (
  22. ErrLocked = errors.New("file already locked")
  23. )
  24. type lock struct {
  25. fd int
  26. file *os.File
  27. }
  28. func (l *lock) Name() string {
  29. return l.file.Name()
  30. }
  31. func (l *lock) TryLock() error {
  32. err := syscall.Flock(l.fd, syscall.LOCK_EX|syscall.LOCK_NB)
  33. if err != nil && err == syscall.EWOULDBLOCK {
  34. return ErrLocked
  35. }
  36. return err
  37. }
  38. func (l *lock) Lock() error {
  39. return syscall.Flock(l.fd, syscall.LOCK_EX)
  40. }
  41. func (l *lock) Unlock() error {
  42. return syscall.Flock(l.fd, syscall.LOCK_UN)
  43. }
  44. func (l *lock) Destroy() error {
  45. return l.file.Close()
  46. }
  47. func NewLock(file string) (Lock, error) {
  48. f, err := os.Open(file)
  49. if err != nil {
  50. return nil, err
  51. }
  52. l := &lock{int(f.Fd()), f}
  53. return l, nil
  54. }