Messing with standard output streams

github logo 惻1 min read

This recently came up at work: capture the STDERR/STDOUT from another process and ship it over a socket somewhere else for archiving and viewing purposes. It was trickier than I expected so Iā€™m writing it down here for next time

#!/usr/bin/env ruby
require 'pty'

r, _, pid = PTY.spawn(ARGV.join(' '))
Thread.new do
  counter = 0
  begin
    loop do
      result = r.read_nonblock(1000)
      counter += 1
      STDOUT.write result
      Thread.new do
        # process result
      end
    end
  rescue IO::WaitReadable
    IO.select([r])
    retry
  rescue EOFError
  end
end
Process.wait
exit_code = $?.to_i
exit(exit_code != 0 ? 1 : 0)
twitter logo DISCUSS
Classic DEV Post from Mar 22

Work faster with Git aliases

Common Git aliases I use every day

david karapetyan profile image
Dispassionate problem solver. I enjoy building minimal and efficient systems. I like to think I don't drink the kool-aid