Ruby:如何获取文件锁定以进行写入? [英] Ruby: How to acquire file lock for writing?
问题描述
我想实现的是这样:
- 如果其他某个进程正在持有该锁,请退出
- 否则获取用于写的锁
我要修改的Ruby代码是
The Ruby code I am trying to modify is.
File.open(filename, "wb") { |inf|
if inf.flock(File::LOCK_EX|File::LOCK_NB) == 0
...
end
}
我可以找到的代码通常使用"rb"
.如果我更改为"wb"
,则会出现问题:因为如果文件上有其他进程正在运行(除非尝试锁定,否则我无法知道),该文件将被File.open(..., "wb")
清除.
The codes I can find are usually using "rb"
. If I change to "wb"
, there is a problem: because if some other process is working on the file (which I cannot know until attempting the lock), the file will be wiped out by File.open(..., "wb")
.
有办法吗?谢谢.
我认为一种方法是使用"File::RDWR|File::CREAT"
,这样您可以先打开文件,而不会擦除其内容,然后尝试锁定.不知道是否还有其他方法,但是"wb"
可能无法工作.我想这是Ruby的尴尬:您必须先打开文件,然后才能获取锁.我认为这两个步骤应该原子化.
I think one way is to use "File::RDWR|File::CREAT"
, so that you can open file first and it won't wipe out its content, then try the lock. Not sure if there is other way, but "wb"
probably will not work. I guess this is an awkwardness of Ruby: you have to open file first before acquiring the lock. I think these two steps should be made atomic.
推荐答案
创建一个锁定文件并将其锁定.如果您的filename
说"path/to/file.txt",请在"path/to/file.txt.lock"上创建一个锁.一旦获得了对锁定文件的锁定,请照常编辑真实文件.
Create a lock file and lock that instead. If your filename
is say "path/to/file.txt" then create a lock on "path/to/file.txt.lock". Once you've acquired your lock on the lock file, edit the real file as normal.
这篇关于Ruby:如何获取文件锁定以进行写入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!