Class: Pidlock

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

Defined Under Namespace

Classes: FileLockedException, ProcessRunning

Instance Attribute Summary collapse

Instance Method Summary collapse

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.expand_path(File.join('/', 'var', 'run', dir, @name))
  @logger = Logger.new(STDERR)
  @file = nil
end

Instance Attribute Details

#loggerObject

Returns the value of attribute logger.



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

def logger
  @logger
end

Instance Method Details

#lockObject



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

#unlockObject



42
43
44
45
# File 'lib/pidlock.rb', line 42

def unlock
  @file.close
  FileUtils.rm_f(@filename)
end