Class: Gin::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/gin/worker.rb

Instance Method Summary collapse

Constructor Details

#initialize(pidfile, &block) ⇒ Worker

Returns a new instance of Worker.


5
6
7
8
9
# File 'lib/gin/worker.rb', line 5

def initialize pidfile, &block
  @pidfile = pidfile
  @pid     = nil
  @block   = block
end

Instance Method Details

#kill(sig = "INT") ⇒ Object


41
42
43
# File 'lib/gin/worker.rb', line 41

def kill sig="INT"
  Process.kill(sig, @pid) if @pid
end

#runObject


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/gin/worker.rb', line 12

def run
  FileUtils.touch(@pidfile)
  f = File.open(@pidfile, 'r+')
  return unless f.flock(File::LOCK_EX | File::LOCK_NB)

  if other_pid = f.read
    running = Process.kill(0, other_pid) rescue false
    return if running
  end

  @pid = fork do
    begin
      f.truncate(File.size(f.path))
      f.write Process.pid.to_s
      f.flush
      @block.call
    rescue Interrupt
      $stderr.puts "Worker Interrupted: #{@pidfile} (#{Process.pid})"
    ensure
      f.close unless f.closed?
      File.delete(f.path)
    end
  end

ensure
  f.close if f && !f.closed?
end

#waitObject


46
47
48
# File 'lib/gin/worker.rb', line 46

def wait
  Process.waitpid(@pid) if @pid
end