Class: Mutagem::Lockfile

Inherits:
Object
  • Object
show all
Defined in:
lib/mutagem/lockfile.rb

Overview

File locking wrapper for Flock

Direct Known Subclasses

Mutex

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lockfile = nil) ⇒ Lockfile

Create a new LockFile

Parameters:

  • lockfile (String) (defaults to: nil)

    filename

Raises:

  • (ArgumentError)


11
12
13
14
# File 'lib/mutagem/lockfile.rb', line 11

def initialize(lockfile=nil)
  raise ArgumentError, "lockfile not specified" unless lockfile
  @lockfile = lockfile
end

Instance Attribute Details

#lockfileObject

filename for the lockfile, can include path



6
7
8
# File 'lib/mutagem/lockfile.rb', line 6

def lockfile
  @lockfile
end

Instance Method Details

#lock(file, mode) ⇒ Boolean

Get a file lock with flock and ensure the lock is removed (but not the lockfile). Accepts an optional code block.

Examples:


open('output', 'w') do |f|
  # exclusive blocking lock
  lock(f, File::LOCK_EX) do |f|
  f << "write to file while blocking other processes"
  end
end

Parameters:

  • file (Object)

    the file IO object returned from a call to “open(filename, mode_string)”

  • mode (Constant)

    locking_constant, see File

Returns:

  • (Boolean)

    0 or false if unable to sucessfully lock



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/mutagem/lockfile.rb', line 44

def lock(file, mode)
  result = file.flock(mode)
  if result
    begin
      yield file if block_given?  # may not have block if called by locked?
    ensure
      # unlock but leave the file on the filesystem
      file.flock(File::LOCK_UN)
    end
  end
  return result
end

#locked?Boolean

Does another process have a lock? True if we can’t get an exclusive lock

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
# File 'lib/mutagem/lockfile.rb', line 18

def locked?
  return false unless File.exists?(lockfile)
  result = false
  open(lockfile, 'w') do |f|
    # exclusive non-blocking lock
    result = !lock(f, File::LOCK_EX | File::LOCK_NB)
  end
  result
end