问题描述
如何获取对文件的专有读取访问权?我已经尝试过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
要使用此软件包,首先,为锁文件创建一个新锁
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中获取文件的排他锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!