class Racecar::Daemon

Attributes

pidfile[R]

Public Class Methods

new(pidfile) click to toggle source
# File lib/racecar/daemon.rb, line 7
def initialize(pidfile)
  raise Racecar::Error, "No pidfile specified" if pidfile.nil?

  @pidfile = pidfile
end

Public Instance Methods

check_pid() click to toggle source
# File lib/racecar/daemon.rb, line 44
def check_pid
  if pidfile?
    case pid_status
    when :running, :not_owned
      $stderr.puts "=> Racecar is already running with that PID file (#{pidfile})"
      exit(1)
    when :dead
      File.delete(pidfile)
    end
  end
end
daemonize!() click to toggle source
# File lib/racecar/daemon.rb, line 17
def daemonize!
  exit if fork
  Process.setsid
  exit if fork
  Dir.chdir "/"
end
pid() click to toggle source
# File lib/racecar/daemon.rb, line 56
def pid
  if File.exists?(pidfile)
    File.read(pidfile).to_i
  else
    nil
  end
end
pid_status() click to toggle source
# File lib/racecar/daemon.rb, line 72
def pid_status
  return :exited if pid.nil?
  return :dead if pid == 0

  # This will raise Errno::ESRCH if the process doesn't exist.
  Process.kill(0, pid)

  :running
rescue Errno::ESRCH
  :dead
rescue Errno::EPERM
  :not_owned
end
pidfile?() click to toggle source
# File lib/racecar/daemon.rb, line 13
def pidfile?
  !pidfile.nil?
end
redirect_output(logfile) click to toggle source
# File lib/racecar/daemon.rb, line 24
def redirect_output(logfile)
  FileUtils.mkdir_p(File.dirname(logfile), mode: 0755)
  FileUtils.touch(logfile)

  File.chmod(0644, logfile)

  $stderr.reopen(logfile, 'a')
  $stdout.reopen($stderr)
  $stdout.sync = $stderr.sync = true
end
running?() click to toggle source
# File lib/racecar/daemon.rb, line 64
def running?
  pid_status == :running || pid_status == :not_owned
end
stop!() click to toggle source
# File lib/racecar/daemon.rb, line 68
def stop!
  Process.kill("TERM", pid)
end
suppress_input() click to toggle source
# File lib/racecar/daemon.rb, line 35
def suppress_input
  $stdin.reopen('/dev/null')
end
suppress_output() click to toggle source
# File lib/racecar/daemon.rb, line 39
def suppress_output
  $stderr.reopen('/dev/null', 'a')
  $stdout.reopen($stderr)
end
write_pid() click to toggle source
# File lib/racecar/daemon.rb, line 86
def write_pid
  File.open(pidfile, ::File::CREAT | ::File::EXCL | ::File::WRONLY) do |f|
    f.write(Process.pid.to_s)
  end

  at_exit do
    File.delete(pidfile) if File.exists?(pidfile)
  end
rescue Errno::EEXIST
  check_pid
  retry
end