Skip to content

Instantly share code, notes, and snippets.

@tompng
Created December 26, 2022 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompng/66c7e41b1ce3da3127da6733eaada256 to your computer and use it in GitHub Desktop.
Save tompng/66c7e41b1ce3da3127da6733eaada256 to your computer and use it in GitHub Desktop.
require'pty'
require'io/console'
PTY.spawn('irb'){|r,w|
echo = true
q = Queue.new
Thread.new{
loop{
if echo != w.echo?
echo = w.echo?
q << [Time.now, echo]
end
sleep 0.01
}
}
close = ->{
r.close rescue nil
w.close rescue nil
q.close rescue nil
}
Thread.new{
loop{
data = STDIN.readpartial 1024
close.call and break unless data
w.write data
} rescue nil
close.call
}
t1 = Thread.new {
loop do
t, data = q.deq
break unless t
time = 0.5 + (t - Time.now)
sleep time if time > 0
case data
when true
STDIN.cooked!
when false
STDIN.raw!
else
STDOUT.write data
end
end rescue nil
close.call
}
t2 = Thread.new{
loop{
data = r.readpartial 1
close.call and break unless data
q << [Time.now, data]
} rescue nil
close.call
}
t1.join
t2.join
close.call
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment