flock_unix.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  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 "golang.org/x/sys/unix"
  16. // Acquire acquires a lock on a file for the duration of the process. This method
  17. // is reentrant.
  18. func Acquire(path string) error {
  19. fd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR, 0600)
  20. if err != nil {
  21. return err
  22. }
  23. // We don't need to close the fd since we should hold
  24. // it until the process exits.
  25. return unix.Flock(fd, unix.LOCK_EX)
  26. }