Class: Utils::Subprocess

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

Instance Method Summary collapse

Constructor Details

#initialize(cmd, &block) ⇒ Subprocess

Returns a new instance of Subprocess.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ssh_scan/subprocess.rb', line 5

def initialize(cmd, &block)
  # see: http://stackoverflow.com/a/1162850/83386
  Open3.popen3(cmd) do |stdin, stdout, stderr, thread|
    # read each stream from a new thread
    { :out => stdout, :err => stderr }.each do |key, stream|
      Thread.new do
        until (line = stream.gets).nil? do
          # yield the block depending on the stream
          if key == :out
            yield line, nil, thread if block_given?
          else
            yield nil, line, thread if block_given?
          end
        end
      end
    end

    thread.join # don't exit until the external process is done
  end
end