lock_unix.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 interface {
  25. Name() string
  26. TryLock() error
  27. Lock() error
  28. Unlock() error
  29. Destroy() error
  30. }
  31. type lock struct {
  32. fd int
  33. file *os.File
  34. }
  35. func (l *lock) Name() string {
  36. return l.file.Name()
  37. }
  38. // TryLock acquires exclusivity on the lock without blocking
  39. func (l *lock) TryLock() error {
  40. err := syscall.Flock(l.fd, syscall.LOCK_EX|syscall.LOCK_NB)
  41. if err != nil && err == syscall.EWOULDBLOCK {
  42. return ErrLocked
  43. }
  44. return err
  45. }
  46. // Lock acquires exclusivity on the lock without blocking
  47. func (l *lock) Lock() error {
  48. return syscall.Flock(l.fd, syscall.LOCK_EX)
  49. }
  50. // Unlock unlocks the lock
  51. func (l *lock) Unlock() error {
  52. return syscall.Flock(l.fd, syscall.LOCK_UN)
  53. }
  54. func (l *lock) Destroy() error {
  55. return l.file.Close()
  56. }
  57. func NewLock(file string) (Lock, error) {
  58. f, err := os.Open(file)
  59. if err != nil {
  60. return nil, err
  61. }
  62. l := &lock{int(f.Fd()), f}
  63. return l, nil
  64. }