Question

This is super simple, but it doesn't appear to be working. I'm using Ruby's File#flock method. First, I lock a file, then I release the lock, then I attempt to lock it again. The second lock fails as if the file was still locked. Here is a direct copy paste from an irb session. I'm using Ruby 2.1.0p0 running on Ubuntu 13.04.

$ irb
>> File.open('/tmp/asdf', 'r+').flock(File::LOCK_EX)
=> 0
>> File.open('/tmp/asdf', 'r+').flock(File::LOCK_UN)
=> 0
>> File.open('/tmp/asdf', 'r+').flock(File::LOCK_EX)
^CIRB::Abort: abort then interrupt!
        from (irb):3:in `call'
        from (irb):3:in `flock'
        from (irb):3
        from /usr/local/rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'

The second LOCK_EX attempt just hangs as it would if the file were still locked. As you can see from the copy-paste above, I had to abort the second attempt with a Ctrl-C.

Any idea why the unlock doesn't work here?

For reference, the reason I need this is because I'm trying to get the equivalent of a Mutex but across processes instead of threads. According to what I read online, a file lock should be sufficient for this.

Was it helpful?

Solution

Actually, I just figured it out right after posting the question. It's quite obvious in retrospect, but the LOCK_UN has to work on the same file handle to work, of course. Like so:

$ irb
>> f = File.open('/tmp/asdf', 'r+')
=> #<File:/tmp/asdf>
>> f.flock(File::LOCK_EX)
=> 0
>> f.flock(File::LOCK_UN)
=> 0
>> f = File.open('/tmp/asdf', 'r+')
=> #<File:/tmp/asdf>
>> f.flock(File::LOCK_EX)
=> 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top