lock_solaris.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 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. var lock syscall.Flock_t
  33. lock.Start = 0
  34. lock.Len = 0
  35. lock.Pid = 0
  36. lock.Type = syscall.F_WRLCK
  37. lock.Whence = 0
  38. lock.Pid = 0
  39. err := syscall.FcntlFlock(uintptr(l.fd), syscall.F_SETLK, &lock)
  40. if err != nil && err == syscall.EAGAIN {
  41. return ErrLocked
  42. }
  43. return err
  44. }
  45. func (l *lock) Lock() error {
  46. var lock syscall.Flock_t
  47. lock.Start = 0
  48. lock.Len = 0
  49. lock.Type = syscall.F_WRLCK
  50. lock.Whence = 0
  51. lock.Pid = 0
  52. return syscall.FcntlFlock(uintptr(l.fd), syscall.F_SETLK, &lock)
  53. }
  54. func (l *lock) Unlock() error {
  55. var lock syscall.Flock_t
  56. lock.Start = 0
  57. lock.Len = 0
  58. lock.Type = syscall.F_UNLCK
  59. lock.Whence = 0
  60. err := syscall.FcntlFlock(uintptr(l.fd), syscall.F_SETLK, &lock)
  61. if err != nil && err == syscall.EAGAIN {
  62. return ErrLocked
  63. }
  64. return err
  65. }
  66. func (l *lock) Destroy() error {
  67. return l.file.Close()
  68. }
  69. func NewLock(file string) (Lock, error) {
  70. f, err := os.OpenFile(file, os.O_WRONLY, 0600)
  71. if err != nil {
  72. return nil, err
  73. }
  74. l := &lock{int(f.Fd()), f}
  75. return l, nil
  76. }