Ruby: How to acquire file lock for writing?

3.1k views Asked by At

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

There are 1 answers

2
Philip Hallstrom On BEST ANSWER

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.