github.com/enetx/g@v1.0.80/internal/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  package filelock
     8  
     9  import (
    10  	"io/fs"
    11  	"syscall"
    12  )
    13  
    14  type lockType int16
    15  
    16  const (
    17  	readLock  lockType = syscall.LOCK_SH
    18  	writeLock lockType = syscall.LOCK_EX
    19  )
    20  
    21  func lock(f File, lt lockType) (err error) {
    22  	for {
    23  		err = syscall.Flock(int(f.Fd()), int(lt))
    24  		if err != syscall.EINTR {
    25  			break
    26  		}
    27  	}
    28  	if err != nil {
    29  		return &fs.PathError{
    30  			Op:   lt.String(),
    31  			Path: f.Name(),
    32  			Err:  err,
    33  		}
    34  	}
    35  	return nil
    36  }
    37  
    38  func unlock(f File) error {
    39  	return lock(f, syscall.LOCK_UN)
    40  }