github.com/openshift/installer@v1.4.17/pkg/clusterapi/internal/process/flock/flock_unix.go (about) 1 //go:build linux || darwin || freebsd || openbsd || netbsd || dragonfly 2 // +build linux darwin freebsd openbsd netbsd dragonfly 3 4 package flock 5 6 import ( 7 "errors" 8 "fmt" 9 "os" 10 11 "golang.org/x/sys/unix" 12 ) 13 14 // Acquire acquires a lock on a file for the duration of the process. This method 15 // is reentrant. 16 func Acquire(path string) error { 17 fd, err := unix.Open(path, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0600) 18 if err != nil { 19 if errors.Is(err, os.ErrExist) { 20 return fmt.Errorf("cannot lock file %q: %w", path, ErrAlreadyLocked) 21 } 22 return err 23 } 24 25 // We don't need to close the fd since we should hold 26 // it until the process exits. 27 err = unix.Flock(fd, unix.LOCK_NB|unix.LOCK_EX) 28 if errors.Is(err, unix.EWOULDBLOCK) { // This condition requires LOCK_NB. 29 return fmt.Errorf("cannot lock file %q: %w", path, ErrAlreadyLocked) 30 } 31 return err 32 }