Skip to content

Instantly share code, notes, and snippets.

@seamusabshere
Created July 28, 2010 16:04
Show Gist options
  • Save seamusabshere/495023 to your computer and use it in GitHub Desktop.
Save seamusabshere/495023 to your computer and use it in GitHub Desktop.
diff --git a/VERSION b/VERSION
index 0c62199..53a75d6 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.2.1
+0.2.6
diff --git a/lib/daemon_spawn.rb b/lib/daemon_spawn.rb
index 2e3d628..f032d55 100644
--- a/lib/daemon_spawn.rb
+++ b/lib/daemon_spawn.rb
@@ -45,15 +45,34 @@ module DaemonSpawn
end
puts "#{daemon.app_name} started."
end
+
+ def self.alive?(pid)
+ Process.kill 0, pid
+ rescue Errno::ESRCH
+ false
+ end
def self.stop(daemon) #:nodoc:
if pid = daemon.pid
FileUtils.rm(daemon.pid_file)
- Process.kill("TERM", pid)
+ Process.kill(daemon.signal, pid)
begin
Process.wait(pid)
rescue Errno::ECHILD
end
+
+ # just in case...
+ ticks = daemon.timeout
+ while ticks > 0 and alive?(pid) do
+ puts "Process is still alive. #{ticks} seconds until I kill -9 it..."
+ sleep 1
+ ticks -= 1
+ end
+ if alive?(pid)
+ puts "Process didn't quit after timeout of #{daemon.timeout} seconds. Killing..."
+ Process.kill 9, pid
+ end
+ # ... ok.
else
puts "PID file not found. Is the daemon started?"
end
@@ -66,10 +85,12 @@ module DaemonSpawn
end
class Base
- attr_accessor :log_file, :pid_file, :sync_log, :working_dir, :app_name, :singleton, :index
+ attr_accessor :log_file, :pid_file, :sync_log, :working_dir, :app_name, :singleton, :index, :signal, :timeout
def initialize(opts = {})
raise 'You must specify a :working_dir' unless opts[:working_dir]
+ self.signal = opts[:signal] || "TERM"
+ self.timeout = opts[:timeout] || 15
self.working_dir = opts[:working_dir]
self.app_name = opts[:application] || classname
self.pid_file = opts[:pid_file] || File.join(working_dir, 'tmp', 'pids', app_name + extension)
@@ -101,12 +122,8 @@ module DaemonSpawn
end
def alive? #:nodoc:
- if File.file?(self.pid_file)
- begin
- Process.kill(0, self.pid)
- rescue Errno::ESRCH, ::Exception
- false
- end
+ if File.file?(pid_file)
+ DaemonSpawn.alive? pid
else
false
end
@@ -156,14 +173,14 @@ module DaemonSpawn
end
end
+ # Start daemons(s) unless at least one is running
def self.start(opts, args)
- daemons = find(opts)
- if daemons.empty?
- daemons = build(opts)
- daemons.map { |d| DaemonSpawn.start(d, args) }
- else
- puts "Daemons already started! PIDS: #{daemons.map {|d| d.pid}.join(', ')}"
+ living_daemons = find(opts).select { |d| d.alive? }
+ if living_daemons.any?
+ puts "Daemons are still alive! PIDS: #{living_daemons.map {|d| d.pid}.join(', ')}"
exit 1
+ else
+ build(opts).map { |d| DaemonSpawn.start(d, args) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment