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.
@return [boolean] true if lock is successfully acquired, false otherwise.
# File lib/puppet/util/lockfile.rb, line 25 def lock(lock_data = nil) begin Puppet::FileSystem.exclusive_create(@file_path, nil) do |fd| fd.print(lock_data) end true rescue Errno::EEXIST false end 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 53 def lock_data return File.read(@file_path) if file_locked? end
# File lib/puppet/util/lockfile.rb, line 45 def locked? # delegate logic to a more explicit private method file_locked? end
# File lib/puppet/util/lockfile.rb, line 36 def unlock if locked? Puppet::FileSystem.unlink(@file_path) true else false end end
# File lib/puppet/util/lockfile.rb, line 12 def initialize(file_path) @file_path = file_path end