Skip to content

Instantly share code, notes, and snippets.

@EricLondon
Created September 12, 2018 18:33
Show Gist options
  • Save EricLondon/5ce2119c41604e2cbec276c4e790b48a to your computer and use it in GitHub Desktop.
Save EricLondon/5ce2119c41604e2cbec276c4e790b48a to your computer and use it in GitHub Desktop.
Ruby stream command output
./parent.rb
command: ./child.rb 1
2018-09-12 14:32:09: stdout
2018-09-12 14:32:09: stderr
2018-09-12 14:32:11: stdout
2018-09-12 14:32:11: stderr
pid 97509 exit 1
97509
false
command: ./child.rb 0
2018-09-12 14:32:13: stdout
2018-09-12 14:32:13: stderr
2018-09-12 14:32:15: stdout
2018-09-12 14:32:15: stderr
pid 97513 exit 0
97513
true
#!/usr/bin/env ruby
exit_status = ARGV[0].to_i
2.times do
time_now = Time.now.strftime('%Y-%m-%d %H:%M:%S')
$stdout.puts "#{time_now}: stdout"
$stderr.puts "#{time_now}: stderr"
sleep 2
end
exit exit_status
#!/usr/bin/env ruby
require 'pty'
def stream_command(command)
puts "command: #{command}"
begin
PTY.spawn(command) do |stdout, stdin, pid|
begin
stdout.each { |line| print line }
rescue Errno::EIO
end
end
rescue PTY::ChildExited
end
# debug:
puts $?
puts $?.pid
puts $?.success?
end
stream_command('./child.rb 1')
stream_command('./child.rb 0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment