flock_unix.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // +build linux darwin freebsd openbsd netbsd dragonfly
  2. /*
  3. Copyright 2016 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package flock
  15. import (
  16. "os"
  17. "sync"
  18. "golang.org/x/sys/unix"
  19. )
  20. var (
  21. // lock guards lockfile. Assignment is not atomic.
  22. lock sync.Mutex
  23. // os.File has a runtime.Finalizer so the fd will be closed if the struct
  24. // is garbage collected. Let's hold onto a reference so that doesn't happen.
  25. lockfile *os.File
  26. )
  27. // Acquire acquires a lock on a file for the duration of the process. This method
  28. // is reentrant.
  29. func Acquire(path string) error {
  30. lock.Lock()
  31. defer lock.Unlock()
  32. var err error
  33. if lockfile, err = os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600); err != nil {
  34. return err
  35. }
  36. opts := unix.Flock_t{Type: unix.F_WRLCK}
  37. if err := unix.FcntlFlock(lockfile.Fd(), unix.F_SETLKW, &opts); err != nil {
  38. return err
  39. }
  40. return nil
  41. }