github.com/searKing/golang/go@v1.2.117/sync/filelock/filelock_unix.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build darwin || dragonfly || freebsd || illumos || linux || netbsd || openbsd
     6  
     7  // Copied from go/gc/src/cmd/go/internal/lockedfile/internal/filelock/filelock_unix.go
     8  
     9  package filelock
    10  
    11  import (
    12  	"io/fs"
    13  	"syscall"
    14  )
    15  
    16  type lockType int16
    17  
    18  const (
    19  	readLock  lockType = syscall.LOCK_SH
    20  	writeLock lockType = syscall.LOCK_EX
    21  )
    22  
    23  func lock(f File, lt lockType, try bool) (err error) {
    24  	if try {
    25  		lt = lt | syscall.LOCK_NB
    26  	}
    27  	for {
    28  		err = syscall.Flock(int(f.Fd()), int(lt))
    29  		if err != syscall.EINTR {
    30  			break
    31  		}
    32  	}
    33  	if err != nil {
    34  		return &fs.PathError{
    35  			Op:   lt.String(),
    36  			Path: f.Name(),
    37  			Err:  err,
    38  		}
    39  	}
    40  	return nil
    41  }
    42  
    43  func unlock(f File) error {
    44  	return lock(f, syscall.LOCK_UN, false)
    45  }