lock_plan9.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. package fileutil
  15. import (
  16. "errors"
  17. "os"
  18. "syscall"
  19. "time"
  20. )
  21. var (
  22. ErrLocked = errors.New("file already locked")
  23. )
  24. type lock struct {
  25. fname string
  26. file *os.File
  27. }
  28. func (l *lock) Name() string {
  29. return l.fname
  30. }
  31. func (l *lock) TryLock() error {
  32. err := os.Chmod(l.fname, syscall.DMEXCL|0600)
  33. if err != nil {
  34. return err
  35. }
  36. f, err := os.Open(l.fname)
  37. if err != nil {
  38. return ErrLocked
  39. }
  40. l.file = f
  41. return nil
  42. }
  43. func (l *lock) Lock() error {
  44. err := os.Chmod(l.fname, syscall.DMEXCL|0600)
  45. if err != nil {
  46. return err
  47. }
  48. for {
  49. f, err := os.Open(l.fname)
  50. if err == nil {
  51. l.file = f
  52. return nil
  53. }
  54. time.Sleep(10 * time.Millisecond)
  55. }
  56. }
  57. func (l *lock) Unlock() error {
  58. return l.file.Close()
  59. }
  60. func (l *lock) Destroy() error {
  61. return nil
  62. }
  63. func NewLock(file string) (Lock, error) {
  64. l := &lock{fname: file}
  65. return l, nil
  66. }