dpv46227 2018-10-25 09:55
浏览 100
已采纳

如何在Go中获取文件的排他锁

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条回答 默认 最新

  • doudi1750 2018-10-26 12:00
    关注

    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()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线