Class: Pidlock
- Inherits:
-
Object
- Object
- Pidlock
- Defined in:
- lib/pidlock.rb
Defined Under Namespace
Classes: FileLockedException, ProcessRunning
Instance Attribute Summary collapse
-
#logger ⇒ Object
Returns the value of attribute logger.
Instance Method Summary collapse
-
#initialize(name) ⇒ Pidlock
constructor
A new instance of Pidlock.
- #lock ⇒ Object
- #unlock ⇒ Object
Constructor Details
#initialize(name) ⇒ Pidlock
Returns a new instance of Pidlock.
11 12 13 14 15 16 17 |
# File 'lib/pidlock.rb', line 11 def initialize(name) dir = File.dirname(name) @name = File.basename(name) @filename = File.(File.join('/', 'var', 'run', dir, @name)) @logger = Logger.new(STDERR) @file = nil end |
Instance Attribute Details
#logger ⇒ Object
Returns the value of attribute logger.
6 7 8 |
# File 'lib/pidlock.rb', line 6 def logger @logger end |
Instance Method Details
#lock ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/pidlock.rb', line 21 def lock unless @file unless (File.writable?(File.dirname(@filename))) @filename = File.join('/', 'tmp', @name) end @file = File.open(@filename, File::RDWR|File::CREAT, 0600) if (old_pid = @file.gets) if (old_process = Sys::ProcTable.ps(old_pid.chomp.to_i)) raise ProcessRunning if old_process.comm == File.basename(@name, File.extname(@name)) else @logger.warn "WARNING: resetting stale lockfile" end end @file.flock(File::LOCK_EX | File::LOCK_NB) or raise FileLockedException @file.rewind @file.truncate(0) @file.write Process.pid @file.flush end end |
#unlock ⇒ Object
42 43 44 45 |
# File 'lib/pidlock.rb', line 42 def unlock @file.close FileUtils.rm_f(@filename) end |