github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/file/lock.go (about)

     1  // Copyright 2021 The TrueBlocks Authors. All rights reserved.
     2  // Use of this source code is governed by a license that can
     3  // be found in the LICENSE file.
     4  
     5  package file
     6  
     7  import (
     8  	"os"
     9  	"time"
    10  	"syscall"
    11  	"errors"
    12  )
    13  
    14  var maxSecondsLock = 3
    15  
    16  var DefaultOpenFlags = os.O_RDWR | os.O_CREATE
    17  var DefaultOpenFlagsAppend = os.O_RDWR | os.O_CREATE | os.O_APPEND
    18  
    19  // WaitOnLock tries to lock a file for maximum `maxSecondsLock`
    20  func WaitOnLock(filePath string, openFlags int) (file *os.File, err error) {
    21  	file, err = os.OpenFile(filePath, openFlags, 0666)
    22  	if err != nil {
    23  		return
    24  	}
    25  
    26  	for i := 0; i < maxSecondsLock; i++ {
    27  		err = Lock(file)
    28  		if err == nil {
    29  			return
    30  		}
    31  		if err == syscall.EAGAIN || err == syscall.EACCES {
    32  			// Another process has already locked the file, we wait
    33  			time.Sleep(500 * time.Millisecond)
    34  			continue
    35  		}
    36  		return file, err
    37  	}
    38  	return file, errors.New("lock timeout")
    39  }