How to get an exclusive lock on a file in go

2020-07-04 06:21发布

问题:

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 other process to have access to read and write while the first process has not closed it explicitly. In .NET I could do something as:

File.Open("a.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);

How do I do it in go?

回答1:

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()
}


标签: go