Skip to content

Instantly share code, notes, and snippets.

@ahawkins
Created December 2, 2013 20:22
Show Gist options
  • Select an option

  • Save ahawkins/7758115 to your computer and use it in GitHub Desktop.

Select an option

Save ahawkins/7758115 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class PidFile
attr_reader :path
def initialize(path)
@path = path
end
def exists?
File.exists? path
end
# Returns true if the process is running
def running?
return false unless exists?
return false unless pid
# Check if process is in existence
# The simplest way to do this is to send signal '0'
# (which is a single system call) that doesn't actually
# send a signal
begin
Process.kill 0, pid
return true
rescue Errno::ESRCH
return false
rescue ::Exception # for example on EPERM (process exists but does not belong to us)
return true
end
end
# Return the pid contained in the pidfile, or nil
def pid
return nil unless exists?
content = File.read(path)
content.empty? ? nil : content.to_i
end
def write
File.open path, 'w' do |f|
f.puts Process.pid
end
end
end
case ARGV.first
when 'start'
pid_file = PidFile.new 'app.pid'
raise "#{pid_file.pid} already running" if pid_file.running?
Process.daemon true, true
pid_file.write
$stdout.reopen "app.log", "a"
$stderr.reopen "app.log", "a"
$stdout.sync = true
$stderr.sync = true
require_relative 'consumer'
when 'stop'
pid_file = PidFile.new 'app.pid'
if !pid_file.running?
$stderr.puts "Process not running"
exit 1
end
Process.kill 'TERM', pid_file.pid
$stdout.puts "Sent TERM to #{pid_file.pid}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment