module LockFile

File locking support

Public Class Methods

create_ex(filename) { |file| ... } click to toggle source

create a new file and return an error if it already exists, otherwise nil

# File lib/whimsy/lockfile.rb, line 10
def self.create_ex(filename)
  err = nil
  begin
    File.open(filename, File::WRONLY|File::CREAT|File::EXCL) do |file|
      yield file
    end
  rescue => e
    err = e
  end
  err
end
flock(file, mode) { |file| ... } click to toggle source

lock an open file and ensure it gets unlocked

# File lib/whimsy/lockfile.rb, line 23
def self.flock(file, mode)
  ok = file.flock(mode)
  if ok
    begin
      yield file
    ensure
      file.flock(File::LOCK_UN)
    end
  end
  ok
end
lockfile(filename, mode=nil, lockmode=nil) { |g| ... } click to toggle source

open a file and lock it filename mode: default ‘r’ lockmode: default LOCK_SH

# File lib/whimsy/lockfile.rb, line 39
def self.lockfile(filename, mode=nil, lockmode=nil)
  open(filename, mode || 'r') do |f|
    self.flock(f, lockmode || File::LOCK_SH) { |g|
      yield g
    }
  end
end