github.com/sunvim/utils@v0.1.0/fs/os_unix.go (about)

     1  //go:build !windows
     2  
     3  package fs
     4  
     5  import (
     6  	"os"
     7  	"syscall"
     8  )
     9  
    10  func createLockFile(name string, perm os.FileMode) (LockFile, bool, error) {
    11  	acquiredExisting := false
    12  	if _, err := os.Stat(name); err == nil {
    13  		acquiredExisting = true
    14  	}
    15  	f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm)
    16  	if err != nil {
    17  		return nil, false, err
    18  	}
    19  	if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
    20  		if err == syscall.EWOULDBLOCK {
    21  			err = os.ErrExist
    22  		}
    23  		return nil, false, err
    24  	}
    25  	return &osLockFile{f, name}, acquiredExisting, nil
    26  }