Skip to content

Instantly share code, notes, and snippets.

@YusukeIwaki
Created December 19, 2019 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YusukeIwaki/a3421a6e0232a1b3d41af11c7815d627 to your computer and use it in GitHub Desktop.
Save YusukeIwaki/a3421a6e0232a1b3d41af11c7815d627 to your computer and use it in GitHub Desktop.
2つ以上のIOストリームをマージする
require 'open3'
Open3.popen3("ping", "google.com") do |stdin, stdout, stderr, wait_thr|
stdin.close
while std_ready_list = IO.select([stderr, stdout])&.first
std_ready_list.each do |std|
puts ">> #{std.readline}"
end
end
end
@YusukeIwaki
Copy link
Author

def popen_listen(*cmd)
  out_r, out_w = IO.pipe
  err_r, err_w = IO.pipe

  child_io = [out_w, err_w]
  spawn_options = { out: out_w, err: err_w }

  pid = spawn(*cmd, **spawn_options)
  child_io.each(&:close)
  return [out_r, err_r, pid]
end

  stdout, stderr, pid = popen_listen("ping", "google.com")
  thr = Process.detach(pid)
  begin
    while std_ready_list = IO.select([stderr, stdout])&.first
      std_ready_list.each do |std|
        puts ">> #{std.readline}"
      end
    end
  rescue EOFError
    puts "eof"
    puts thr
  ensure
    [stdout, stderr].each{|io| io.close unless io.closed?}
    thr.join
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment