Last active
March 16, 2018 18:42
-
-
Save twolfson/c8e5c7253f5439b1bf16b2f85bdddcab to your computer and use it in GitHub Desktop.
Pipe child process stdout and stderr to main process in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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