如何在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?
如何在go中获得对文件的专有读取访问权限? 我已经尝试过docs中的文档,但是我仍然能够在记事本中打开文件并进行编辑。 我想拒绝任何其他进程具有读写权限,而第一个进程没有明确关闭它。 在.NET中,我可以执行以下操作: p>
File.Open(“ a.txt”,FileMode.Open,FileAccess.ReadWrite,FileShare.None);
代码> pre>
我该如何进行呢? p>
div>
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()
}