Class: Spork::Forker

Inherits:
Object
  • Object
show all
Defined in:
lib/spork/forker.rb

Defined Under Namespace

Classes: ForkDiedException

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Forker

Returns a new instance of Forker.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/spork/forker.rb', line 3

def initialize(&block)
  return unless block_given?
  @child_io, @server_io = UNIXSocket.socketpair
  @child_pid = Kernel.fork do
    @server_io.close
    Marshal.dump(yield, @child_io)
    # wait for the parent to acknowledge receipt of the result.
    master_response = 
      begin
        Marshal.load(@child_io)
      rescue EOFError
        nil
      end
    
    # terminate, skipping any at_exit blocks.
    exit!(0)
  end
  @child_io.close
end

Instance Method Details

#abortObject



39
40
41
42
43
44
45
# File 'lib/spork/forker.rb', line 39

def abort
  if running?
    Process.kill(Signal.list['TERM'], @child_pid)
    @child_pid = nil
    true
  end
end

#resultObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/spork/forker.rb', line 23

def result
  return unless running?
  result_thread = Thread.new do
    begin
      @result = Marshal.load(@server_io)
      Marshal.dump('ACK', @server_io)
    rescue ForkDiedException
      @result = nil
    end
  end
  Process.wait(@child_pid)
  result_thread.raise(ForkDiedException) if @result.nil?
  @child_pid = nil
  @result
end

#running?Boolean

Returns:

  • (Boolean)


47
48
49
50
51
52
53
# File 'lib/spork/forker.rb', line 47

def running?
  return false unless @child_pid
  Process.getpgid(@child_pid)
  true
rescue Errno::ESRCH
  false
end