Class: VCAP::PidFile

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

Overview

Helper class to atomically create/update pidfiles and ensure that only one instance of a given process is running at all times.

NB: Ruby doesn’t have real destructors so if you want to be polite and clean up after yourself be sure to call unlink() before your process exits.

usage:

begin

pidfile = VCAP::PidFile.new('/tmp/foo')

rescue => e

puts "Error creating pidfile: %s" % (e)
exit(1)

end

Defined Under Namespace

Classes: ProcessRunningError

Instance Method Summary collapse

Constructor Details

#initialize(pid_file, create_parents = true) ⇒ PidFile

Returns a new instance of PidFile.



158
159
160
161
162
# File 'lib/vcap/common.rb', line 158

def initialize(pid_file, create_parents=true)
  @pid_file = pid_file
  @dirty = true
  write(create_parents)
end

Instance Method Details

#to_sObject



192
193
194
# File 'lib/vcap/common.rb', line 192

def to_s()
  @pid_file
end

Removes the created pidfile



165
166
167
168
169
170
171
172
173
174
175
# File 'lib/vcap/common.rb', line 165

def unlink()
  return unless @dirty

  # Swallowing exception here is fine. Removing the pid files is a courtesy.
  begin
    File.unlink(@pid_file)
    @dirty = false
  rescue
  end
  self
end


187
188
189
190
# File 'lib/vcap/common.rb', line 187

def unlink_at_exit()
  at_exit { unlink() }
  self
end

Removes the created pidfile upon receipt of the supplied signals



178
179
180
181
182
183
184
185
# File 'lib/vcap/common.rb', line 178

def unlink_on_signals(*sigs)
  return unless @dirty

  sigs.each do |s|
    Signal.trap(s) { unlink() }
  end
  self
end