diff options
author | mpalmer <mpalmer@980ebf18-57e1-0310-9a29-db15c13687c0> | 2006-12-31 04:07:48 +0000 |
---|---|---|
committer | mpalmer <mpalmer@980ebf18-57e1-0310-9a29-db15c13687c0> | 2006-12-31 04:07:48 +0000 |
commit | e2525058b69fc07d4cb336b15f9a8afbd9e718b5 (patch) | |
tree | 87b93c428ec4511a0af704444408bc43d5da8fc3 /lib | |
parent | c1035ccb7e0eb04c68b6e95b877f700d828b3be9 (diff) | |
download | puppet-e2525058b69fc07d4cb336b15f9a8afbd9e718b5.tar.gz puppet-e2525058b69fc07d4cb336b15f9a8afbd9e718b5.tar.xz puppet-e2525058b69fc07d4cb336b15f9a8afbd9e718b5.zip |
Add a Puppet::Util::Pidlock class, for use by locks and PID files
git-svn-id: https://reductivelabs.com/svn/puppet/trunk@2000 980ebf18-57e1-0310-9a29-db15c13687c0
Diffstat (limited to 'lib')
-rw-r--r-- | lib/puppet/util/pidlock.rb | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/lib/puppet/util/pidlock.rb b/lib/puppet/util/pidlock.rb new file mode 100644 index 000000000..be7e1dbca --- /dev/null +++ b/lib/puppet/util/pidlock.rb @@ -0,0 +1,68 @@ +require 'fileutils' + +class Puppet::Util::Pidlock + attr_reader :lockfile + + def initialize(lockfile) + @lockfile = lockfile + end + + def locked? + clear_if_stale + File.exists? @lockfile + end + + def mine? + Process.pid == lock_pid + end + + def anonymous? + return false unless File.exists?(@lockfile) + File.read(@lockfile) == "" + end + + def lock(opts = {}) + opts = {:anonymous => false}.merge(opts) + + if locked? + false + else + if opts[:anonymous] + File.open(@lockfile, 'w') { |fd| true } + else + File.open(@lockfile, "w") { |fd| fd.write(Process.pid) } + end + true + end + end + + def unlock(opts = {}) + opts = {:anonymous => false}.merge(opts) + + if mine? or (opts[:anonymous] and anonymous?) + File.unlink(@lockfile) + true + else + false + end + end + + private + def lock_pid + if File.exists? @lockfile + File.read(@lockfile).to_i + else + nil + end + end + + def clear_if_stale + return if lock_pid.nil? + + begin + Process.kill(0, lock_pid) + rescue Errno::ESRCH + File.unlink(@lockfile) + end + end +end |