lock_solaris.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 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. var lock syscall.Flock_t
  41. lock.Start = 0
  42. lock.Len = 0
  43. lock.Pid = 0
  44. lock.Type = syscall.F_WRLCK
  45. lock.Whence = 0
  46. lock.Pid = 0
  47. err := syscall.FcntlFlock(uintptr(l.fd), syscall.F_SETLK, &lock)
  48. if err != nil && err == syscall.EAGAIN {
  49. return ErrLocked
  50. }
  51. return err
  52. }
  53. // Lock acquires exclusivity on the lock without blocking
  54. func (l *lock) Lock() error {
  55. var lock syscall.Flock_t
  56. lock.Start = 0
  57. lock.Len = 0
  58. lock.Type = syscall.F_WRLCK
  59. lock.Whence = 0
  60. lock.Pid = 0
  61. return syscall.FcntlFlock(uintptr(l.fd), syscall.F_SETLK, &lock)
  62. }
  63. // Unlock unlocks the lock
  64. func (l *lock) Unlock() error {
  65. var lock syscall.Flock_t
  66. lock.Start = 0
  67. lock.Len = 0
  68. lock.Type = syscall.F_UNLCK
  69. lock.Whence = 0
  70. err := syscall.FcntlFlock(uintptr(l.fd), syscall.F_SETLK, &lock)
  71. if err != nil && err == syscall.EAGAIN {
  72. return ErrLocked
  73. }
  74. return err
  75. }
  76. func (l *lock) Destroy() error {
  77. return l.file.Close()
  78. }
  79. func NewLock(file string) (Lock, error) {
  80. f, err := os.OpenFile(file, os.O_WRONLY, 0600)
  81. if err != nil {
  82. return nil, err
  83. }
  84. l := &lock{int(f.Fd()), f}
  85. return l, nil
  86. }