class Opener::Daemons::Pidfile

Class for writing and retrieving PID files as well as managing the associated process.

@!attribute [r] path

The path to store the PID in.
@return [String]

Attributes

path[R]

Public Class Methods

new(path) click to toggle source

@param [String] path

# File lib/opener/daemons/pidfile.rb, line 17
def initialize(path)
  @path = path
end

Public Instance Methods

alive?() click to toggle source

Returns `true` if the associated process is alive.

@return [TrueClass|FalseClass]

# File lib/opener/daemons/pidfile.rb, line 72
def alive?
  id = read

  begin
    Process.kill(0, id)

    return true
  rescue Errno::ESRCH, Errno::EPERM
    return false
  end
end
read() click to toggle source

Reads and returns the process ID.

@return [Fixnum]

# File lib/opener/daemons/pidfile.rb, line 41
def read
  return File.read(path).to_i
end
terminate() click to toggle source

Terminates the process by sending it the TERM signal and waits for it to shut down.

# File lib/opener/daemons/pidfile.rb, line 56
def terminate
  id = read

  begin
    Process.kill('TERM', id)
    Process.wait(id)
  rescue Errno::ESRCH, Errno::ECHILD
    # Process terminated, yay. Any other error is re-raised.
  end
end
write(id) click to toggle source

Writes the given process ID to `@path`.

@param [Fixnum] id

# File lib/opener/daemons/pidfile.rb, line 26
def write(id)
  File.open(path, 'w') do |handle|
    handle.write(id.to_s)
  end

# Kill the process immediately if we couldn't write the PID
rescue Errno::ENOENT, Errno::EPERM => error
  Process.kill('KILL', id)
end