Class: TTY::Command::ProcessRunner

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/command/process_runner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cmd, printer, &block) ⇒ ProcessRunner

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize a Runner object

Parameters:

  • the printer to use for logging

API:

  • private



21
22
23
24
25
26
27
28
29
# File 'lib/tty/command/process_runner.rb', line 21

def initialize(cmd, printer, &block)
  @cmd     = cmd
  @timeout = cmd.options[:timeout]
  @input   = cmd.options[:input]
  @signal  = cmd.options[:signal] || "SIGKILL"
  @binmode = cmd.options[:binmode]
  @printer = printer
  @block   = block
end

Instance Attribute Details

#cmdObject (readonly)

the command to be spawned



13
14
15
# File 'lib/tty/command/process_runner.rb', line 13

def cmd
  @cmd
end

Instance Method Details

#run!Object

Execute child process

Write the input if provided to the child’s stdin and read the contents of both the stdout and stderr.

If a block is provided then yield the stdout and stderr content as its being read.

API:

  • public



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/tty/command/process_runner.rb', line 40

def run!
  @printer.print_command_start(cmd)
  start = Time.now

  pid, stdin, stdout, stderr = ChildProcess.spawn(cmd)

  write_stream(stdin, @input)

  stdout_data, stderr_data = read_streams(stdout, stderr)

  status = waitpid(pid)
  runtime = Time.now - start

  @printer.print_command_exit(cmd, status, runtime)

  Result.new(status, stdout_data, stderr_data, runtime)
ensure
  [stdin, stdout, stderr].each { |fd| fd.close if fd && !fd.closed? }
  if pid # Ensure no zombie processes
    ::Process.detach(pid)
    terminate(pid)
  end
end

#terminate(pid) ⇒ Object

Stop a process marked by pid

Parameters:

API:

  • public



69
70
71
# File 'lib/tty/command/process_runner.rb', line 69

def terminate(pid)
  ::Process.kill(@signal, pid) rescue nil
end