How to get an exclusive lock on a file in go

后端 未结 1 2109
慢半拍i
慢半拍i 2021-02-13 20:39

How can I get an exclusive read access to a file in go? I have tried documentations from docs but I am still able to open the file in notepad and edit it. I want to deny any oth

相关标签:
1条回答
  • 2021-02-13 21:11

    I finally found a go package that can lock a file.

    Here is the repo: https://github.com/juju/fslock

    go get -u github.com/juju/fslock
    

    this package does exactly what it says

    fslock provides a cross-process mutex based on file locks that works on windows and *nix platforms. fslock relies on LockFileEx on Windows and flock on *nix systems. The timeout feature uses overlapped IO on Windows, but on *nix platforms, timing out requires the use of a goroutine that will run until the lock is acquired, regardless of timeout. If you need to avoid this use of goroutines, poll TryLock in a loop.

    To use this package, first, create a new lock for the lockfile

    func New(filename string) *Lock
    

    This API will create the lockfile if it already doesn't exist.

    Then we can use the lockhandle to lock (or try lock) the file

    func (l *Lock) Lock() error
    

    There is also a timeout version of the above function that will try to get the lock of the file until timeout

    func (l *Lock) LockWithTimeout(timeout time.Duration) error
    

    Finally, if you are done, release the acquired lock by

    func (l *Lock) Unlock() error
    

    Very basic implementation

    package main
    
    import (
        "time"
        "fmt"
        "github.com/juju/fslock"
    )
    
    func main() {
        lock := fslock.New("../lock.txt")
        lockErr := lock.TryLock()
        if lockErr != nil {
            fmt.Println("falied to acquire lock > " + lockErr.Error())
            return
        }
    
        fmt.Println("got the lock")
        time.Sleep(1 * time.Minute)
    
        // release the lock
        lock.Unlock()
    }
    
    0 讨论(0)
提交回复
热议问题