Module: File::Lock

Included in:
File
Defined in:
lib/vex/base/filesystem/lock.rb

Defined Under Namespace

Modules: Etest

Instance Method Summary collapse

Instance Method Details

#locked(path, &block) ⇒ Object

File.locked implements recursive locking based on lock files.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/vex/base/filesystem/lock.rb', line 4

def locked(path, &block)
  file = File.open "#{path}.lck", "w+"
  begin
    # First try to lock the file nonblockingly.
    # Failing that it might be already locked by *this* process. 
    # Otherwise it is locked by someone else.
    if locked = file.flock(File::LOCK_EX | File::LOCK_NB)
      File.write("#{path}.pid", Thread.uid)
    elsif File.read("#{path}.pid") == Thread.uid
      # already locked by us.
    else
      locked = file.flock(File::LOCK_EX)
    end

    yield
  ensure
    file.flock(File::LOCK_UN) if locked
  end
end