Class: RBWatch::ProcessManager

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

Constant Summary collapse

DEFAULT_GRACE_PERIOD =
2.0
DEFAULT_KILL_TIMEOUT =
5.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command:, stdout: $stdout, stderr: $stderr, grace_period: DEFAULT_GRACE_PERIOD, kill_timeout: DEFAULT_KILL_TIMEOUT, chdir: Dir.pwd) ⇒ ProcessManager

Returns a new instance of ProcessManager.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rbwatch/process_manager.rb', line 10

def initialize(
  command:,
  stdout: $stdout,
  stderr: $stderr,
  grace_period: DEFAULT_GRACE_PERIOD,
  kill_timeout: DEFAULT_KILL_TIMEOUT,
  chdir: Dir.pwd
)
  @command = Array(command).map(&:to_s)
  @child_stdout = stdout
  @child_stderr = stderr
  @grace_period = grace_period.to_f
  @kill_timeout = kill_timeout.to_f
  @chdir = chdir
  @pid = nil
  @last_status = nil
end

Instance Attribute Details

#commandObject (readonly)

Returns the value of attribute command.



8
9
10
# File 'lib/rbwatch/process_manager.rb', line 8

def command
  @command
end

#last_statusObject (readonly)

Returns the value of attribute last_status.



8
9
10
# File 'lib/rbwatch/process_manager.rb', line 8

def last_status
  @last_status
end

#pidObject (readonly)

Returns the value of attribute pid.



8
9
10
# File 'lib/rbwatch/process_manager.rb', line 8

def pid
  @pid
end

Instance Method Details

#poll_statusObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rbwatch/process_manager.rb', line 56

def poll_status
  current_pid = @pid
  return nil unless current_pid

  waited_pid, status = Process.waitpid2(current_pid, Process::WNOHANG)
  return nil unless waited_pid

  @pid = nil
  @last_status = status
  status
rescue Errno::ECHILD
  @pid = nil
  nil
end

#restartObject



46
47
48
49
# File 'lib/rbwatch/process_manager.rb', line 46

def restart
  stop
  start
end

#running?Boolean

Returns:

  • (Boolean)


51
52
53
54
# File 'lib/rbwatch/process_manager.rb', line 51

def running?
  poll_status
  !@pid.nil?
end

#startObject

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
# File 'lib/rbwatch/process_manager.rb', line 28

def start
  raise ArgumentError, "command cannot be empty" if command.empty?

  stop if running?
  @last_status = nil
  @pid = spawn_process
end

#stopObject



36
37
38
39
40
41
42
43
44
# File 'lib/rbwatch/process_manager.rb', line 36

def stop
  current_pid = @pid
  return @last_status unless current_pid

  status = terminate_process(current_pid)
  @pid = nil
  @last_status = status if status
  status
end