Class: ForkingThread

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

Overview

A wrapper for forked processes that imitates some of the Thread class’s interface.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &blk) ⇒ ForkingThread

Returns a new instance of ForkingThread.



9
10
11
12
13
14
15
16
# File 'lib/forkingthread.rb', line 9

def initialize *args, &blk
  warn "ForkingThread#new doesn't support args" unless args.empty?

  @pid = fork(&blk)
  @dead = false
  @status = nil
  @name = nil
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



18
19
20
# File 'lib/forkingthread.rb', line 18

def name
  @name
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
# File 'lib/forkingthread.rb', line 44

def alive?
  return false if @dead
  result = Process.wait2(@pid, Process::WNOHANG) rescue nil
  if result
    @dead = true
    @status = result[1]
    return false
  end
  true
end

#join(limit = nil) ⇒ Object



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

def join limit=nil
  return self if @dead
  if limit.nil?
    # wait indefinitely
    result = Process.wait2(@pid, 0) rescue nil
  elsif limit > 0
    # wait for up to some number of seconds
    result = Timeout::timeout(limit) { Process.wait2(@pid, 0) } rescue nil
  else
    # return immediately
    result = Process.wait2(@pid, Process::WNOHANG) rescue nil
  end
  if result
    @dead = true
    @status = result[1]
    return self
  end
end

#killObject



39
40
41
42
# File 'lib/forkingthread.rb', line 39

def kill
  Process.kill('KILL', @pid) rescue nil
  self
end

#native_thread_idObject



63
64
65
# File 'lib/forkingthread.rb', line 63

def native_thread_id
  alive? ? @pid : nil
end

#statusObject



55
56
57
# File 'lib/forkingthread.rb', line 55

def status
  alive? ? "run" : (@status&.success? ? false : nil)
end

#stop?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/forkingthread.rb', line 59

def stop?
  !alive?
end