Skip to content

Instantly share code, notes, and snippets.

@wnd
Created April 29, 2013 14:56
Show Gist options
  • Save wnd/79c9e8b4bb9d4d6482ff to your computer and use it in GitHub Desktop.
Save wnd/79c9e8b4bb9d4d6482ff to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
# vim: ai ts=2 sts=2 sw=2 expandtab
require 'pty'
require 'time'
exit 1 if ARGV.count == 0
output = ARGV.first
if ARGV.count == 1
File.delete(output) if File.exists?(output)
cmd = "ruby #{__FILE__} #{output} x" # ok
cmd = "ruby #{__FILE__} #{output} x 2>&1" # not ok
timeout = 1.0
stdin, stdout, pid = PTY.spawn(cmd)
timeout_at = Time.now + timeout
loop do
begin
data = stdin.read_nonblock(1024)
print data
timeout_at = Time.now + timeout
rescue Errno::EAGAIN
sleep 0.1
rescue EOFError
$stderr.puts "\nprocess EOF?"
Process.wait(pid)
raise
rescue Errno::EIO
x = Process.wait(pid)
exit $?.exitstatus
end
if Time.now >= timeout_at
puts
puts "output size before: #{File.size?(output)}"
Process.kill('HUP', pid)
puts "output size during: #{File.size?(output)}"
Process.wait(pid)
puts "output size after (1): #{File.size?(output)}"
sleep 1.0 # XXX: magic sleep
puts "output size after (2): #{File.size?(output)}"
exit 1
end
end
else
File.open(output, 'w') do |file|
trap("HUP") do
file.puts "END"
file.flush
exit
end
file.puts "a"
file.flush
$stdout.puts "out"
$stderr.puts "err"
sleep 1.5
file.puts "not reached"
file.flush
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment