Skip to content

Instantly share code, notes, and snippets.

@twolfson
Last active March 16, 2018 18:42
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 twolfson/c8e5c7253f5439b1bf16b2f85bdddcab to your computer and use it in GitHub Desktop.
Save twolfson/c8e5c7253f5439b1bf16b2f85bdddcab to your computer and use it in GitHub Desktop.
Pipe child process stdout and stderr to main process in Ruby
Open3.popen3("./tmp.sh") do |stdin, stdout, stderr, wait_thr|
# Stream output
# DEV: We'd like to stream both `stderr` and `stdout` but it was getting troublesome
# with `.alive?` and `gets()` blocking each other
while line = stdout.gets()
$stdout.puts(line)
end
# Finish any last stderr or stdout
stdout_remainder = stdout.read()
if stdout_remainder != ""
$stdout.puts(stdout_remainder)
end
stderr_remainder = stderr.read()
if stderr_remainder != ""
$stderr.puts(stderr_remainder)
end
# If we had a non-zero exit status, exit similarly
exitstatus = wait_thr.value.exitstatus
if exitstatus != 0
$stderr.puts("Exited with non-zero exit status: #{exitstatus}")
exit(exitstatus)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment