Skip to content

Instantly share code, notes, and snippets.

@spchamp
Created November 6, 2021 09:53
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 spchamp/92704f7040ff003ddc4e64d4c3af9724 to your computer and use it in GitHub Desktop.
Save spchamp/92704f7040ff003ddc4e64d4c3af9724 to your computer and use it in GitHub Desktop.
Ruby I/O - capturing output of a subprocess on separate stdout and stderr descriptors
## (No Warranty)
class SHFrob02
def self.runfrob()
out_rd, out_wr = IO.pipe
err_rd, err_wr = IO.pipe
subpid = Process.spawn("ls -d /frob /etc", :in => :close, :out => out_wr, :err => err_wr )
samepid, status = Process.wait2(subpid)
puts status
out = IO.new(out_rd.to_i, "r")
err = IO.new(err_rd.to_i, "r")
out_wr.close
err_wr.close
out.each_line do |txt|
puts "Out: #{txt}"
end
err.each_line do |txt|
puts "Err: #{txt}"
end
return status
ensure
## NB fails (EBADF) during close
# out.closed? || out.close
# err.closed? || err.close
out_wr.close
err_wr.close
out_rd.close
err_rd.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment