如何在Go中获取文件的排他锁 [英] How to get an exclusive lock on a file in go

查看:39
本文介绍了如何在Go中获取文件的排他锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取对文件的专有读取访问权?我已经尝试过docs中的文档,但是我仍然能够在记事本中打开文件并进行编辑.我想拒绝任何其他进程具有读写权限,而第一个进程没有明确关闭它.在.NET中,我可以执行以下操作:

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);

我该怎么办?

推荐答案

我终于找到了可以锁定文件的go包.

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

这是仓库: https://github.com/juju/fslock

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

go get -u github.com/juju/fslock

此程序包完全按照其说明

this package does exactly what it says

fslock提供了基于有效文件锁的跨进程互斥锁在Windows和* nix平台上.fslock在Windows上依赖LockFileEx并在* nix系统上蜂拥而至.超时功能使用重叠的IOWindows,但在* nix平台上,超时要求使用goroutine将一直运行到获取锁为止,而与超时.如果您需要避免使用goroutine,请在以下位置轮询TryLock循环.

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

如果该锁文件不存在,此API将创建该锁文件.

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

然后我们可以使用lockhandle锁定(或尝试锁定)文件

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

非常基本的实现

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中获取文件的排他锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆