This class provides a simple API for managing a lock file whose contents are an (optional) String. In addition to querying the basic state (#locked?) of the lock, managing the lock (#lock, unlock), the contents can be retrieved at any time while the lock is held (#lock_data). This can be used to store pids, messages, etc.
# File lib/puppet/util/lockfile.rb, line 12 def initialize(file_path) @file_path = file_path end
@return [boolean] true if lock is successfully acquired, false otherwise.
# File lib/puppet/util/lockfile.rb, line 25 def lock(lock_data = nil) return false if locked? File.open(@file_path, 'w') { |fd| fd.print(lock_data) } true end
Retrieve the (optional) lock data that was specified at the time the file
was locked.
@return [String] the data object.
# File lib/puppet/util/lockfile.rb, line 49 def lock_data return File.read(@file_path) if file_locked? end
# File lib/puppet/util/lockfile.rb, line 41 def locked? # delegate logic to a more explicit private method file_locked? end
# File lib/puppet/util/lockfile.rb, line 32 def unlock if locked? File.unlink(@file_path) true else false end end