All pastes #363324 Raw Edit

Something

public text v1 · immutable
·published 2007-02-19 09:39 UTC
rendered paste body
#!/usr/bin/env ruby

# Runs a given application and reroutes the standard output
# to a TCP port.
#
# Windows' popen() implementation hangs when using several threads
# in ruby, therefore use this minimal process to forward the
# output to a TCP port.
#
# Syntax:
#   forwardtoport.rb <port> <command> ...
# Example:
#   forwardtoport.rb 2000 cmd /c dir

require 'socket'

module Shell
  def self.escape(string)
    string !~ %r{[ "\\]}i ? 
      string :
      '"' + string.gsub(%r{(["\\])}i, '\\\\\1') + '"'
  end
end

port = ARGV.shift.to_i
client = TCPSocket.new("localhost", port)

verbose = false
if ARGV[0] == "--verbose"
  verbose = true
  ARGV.shift
end

cmd = ARGV.collect { |a| Shell.escape(a) }.join(" ")
puts cmd if verbose
#client.syswrite(cmd + "\n")

IO.popen(cmd, "r") { |io|
  pid = io.pid
  at_exit {
    begin
      Process.kill(9, pid)
    rescue Errno::EPERM
      # Process might already be killed
    end
  }
  while line = io.gets
    client.syswrite(line)
  end
}

client.close