Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

first

  • Loading branch information...
commit 9a09b1416e74b8fdf4eeab1b1a95c9ccb694b62b 0 parents
Mikhail Kuzmin authored May 22, 2012
4  .gitignore
... ...
@@ -0,0 +1,4 @@
  1
+supervisor.log
  2
+*.txt
  3
+*.st*
  4
+*~
8  run.rb
... ...
@@ -0,0 +1,8 @@
  1
+load 'test.rb'
  2
+
  3
+s = Supervisor.new
  4
+s.daemons << Daemon.new
  5
+s.daemons << Daemon.new
  6
+s.daemons << Daemon.new
  7
+
  8
+s.run
80  test.rb
... ...
@@ -0,0 +1,80 @@
  1
+class BaseDaemon
  2
+  attr_accessor :pid
  3
+
  4
+  def initialize(options = {})
  5
+    @options = options
  6
+  end
  7
+  
  8
+  def started?
  9
+    return false unless @pid
  10
+
  11
+    Process.getpgid( @pid )
  12
+    true
  13
+  rescue Errno::ESRCH
  14
+    false
  15
+  end
  16
+
  17
+  def action
  18
+    raise 'Not Implemented'
  19
+  end
  20
+
  21
+  def perform
  22
+    while true do
  23
+      action
  24
+    end
  25
+  end
  26
+  
  27
+  def run(do_exit = true)
  28
+    return if started?
  29
+    @started = true
  30
+    @pid = fork do
  31
+      @pid = Process.pid
  32
+
  33
+      #STDIN.reopen File.open("#{@pid}.stdin", 'w')
  34
+      STDOUT.reopen File.open("#{@pid}.stout", 'a')
  35
+      STDERR.reopen File.open("#{@pid}.stderr", 'a')
  36
+
  37
+      perform
  38
+    end
  39
+    puts "#{@pid} start"
  40
+    Process.detach(@pid)
  41
+  end
  42
+
  43
+  def stop
  44
+    return unless started?
  45
+    @started = false
  46
+    Process.kill 'QUIT', pid
  47
+  end
  48
+end
  49
+
  50
+class Supervisor < BaseDaemon
  51
+  attr_accessor :daemons
  52
+
  53
+  def initialize(options = {})
  54
+    super
  55
+    @daemons = []
  56
+  end
  57
+
  58
+  def action
  59
+    @daemons.each do |daemon|
  60
+      file_name = "supervisor.log"
  61
+      unless daemon.started?
  62
+        old_pid = daemon.pid
  63
+        File.open file_name, 'a' do |f|
  64
+          daemon.run false
  65
+          f.write "daemon died! pid: #{old_pid}\n"
  66
+          f.write "daemon started! pid: #{daemon.pid}\n"
  67
+        end
  68
+      end
  69
+    end
  70
+    sleep 2
  71
+  end
  72
+end
  73
+
  74
+
  75
+class Daemon < BaseDaemon
  76
+  def action
  77
+    exit!1 if rand(5) == 0
  78
+    sleep 3
  79
+  end
  80
+end

0 notes on commit 9a09b14

Please sign in to comment.
Something went wrong with that request. Please try again.