Ruby: How to acquire file lock for writing?

泄露秘密 提交于 2019-12-11 07:40:22

问题


What I want to achieve is this:

  1. if some other process is holding the lock, quit
  2. otherwise acquire the lock for writing

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
}

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").

Is there a way? Thanks.

New Info

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.


回答1:


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.



来源:https://stackoverflow.com/questions/27306323/ruby-how-to-acquire-file-lock-for-writing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!