class PidFileBlock

Attributes

pid_file_full_name[R]

Public Class Methods

new(piddir: '/run', pidfile:) click to toggle source
# File lib/pid_file_block.rb, line 8
def initialize(piddir: '/run', pidfile:)
  pidfile ||= File.basename($0, '.*')
  @pid_file_full_name = File.join(piddir, pidfile)
end

Public Instance Methods

kill(signal: "TERM") click to toggle source
# File lib/pid_file_block.rb, line 64
def kill(signal: "TERM")
    pid = nil
    File.open(@pid_file_full_name, 'r') do |f|
      f.flock(File::LOCK_SH)
      pid_str = f.read
      begin
        pid = Integer(pid_str)
      rescue ArgumentError
        return false
      end    
    end
    Process.kill(signal, pid)
    return pid
end
open() { || ... } click to toggle source
# File lib/pid_file_block.rb, line 13
def open
  loop do
    begin
      File.open(@pid_file_full_name, 'r') do |f|
        f.flock(File::LOCK_EX)
        if process_running?(f)
          # f.flock(File::LOCK_UN)
          raise PidFileBlock::ProcessExistsError
        end
        unlink_pid_file_if_exists
      end
    rescue Errno::ENOENT
    end
    begin
      File.open(@pid_file_full_name,
                File::Constants::RDWR|File::Constants::CREAT|File::Constants::EXCL) do |f|
        f.flock(File::LOCK_EX)
        if process_running?(f)
          f.flock(File::LOCK_UN)
          raise PidFileBlock::ProcessExistsError
        end
        write_pid(f)
        f.flock(File::LOCK_UN)
      end
      break
    rescue Errno::EEXIST
    end
  end
  yield
  unlink_pid_file_if_exists
end
release() click to toggle source
# File lib/pid_file_block.rb, line 45
def release
  our_pid = $$
  File.open(@pid_file_full_name, 'r') do |f|
    f.flock(File::LOCK_SH)
    file_pid_str = f.read
    begin
      file_pid = Integer(file_pid_str)
    rescue ArgumentError
      return false
    end      
    if file_pid == our_pid
      unlink_pid_file_if_exists
      return true
    else
      return false
    end
  end
end

Private Instance Methods

process_running?(file_handle) click to toggle source
# File lib/pid_file_block.rb, line 88
def process_running?(file_handle)
  file_handle.seek(0)
  pid_str = file_handle.read
  begin
    pid = Integer(pid_str)
    if Process.getpgid(pid)
      return true
    end
  rescue Errno::ESRCH
    return false
  rescue ArgumentError
    return false
  end
  raise 'Program Logic Error'
end
write_pid(file_handle) click to toggle source
# File lib/pid_file_block.rb, line 104
def write_pid(file_handle)
  pid = $$
  file_handle.truncate(0)
  file_handle.write(pid)
end