Skip to content

Instantly share code, notes, and snippets.

@ddrscott
Created July 30, 2017 17:21
Show Gist options
  • Save ddrscott/ae6e9b8ebb99c4c19f6a9353f98fbcf2 to your computer and use it in GitHub Desktop.
Save ddrscott/ae6e9b8ebb99c4c19f6a9353f98fbcf2 to your computer and use it in GitHub Desktop.
open3 async test
require 'open3'
require 'benchmark'
Thread.abort_on_exception = true
lamb = lambda do |input, out, _thread|
output_thread = Thread.new do
log 'output thread started'
out.each_line do |line|
log line.strip
end
end
log 'sending data to stdin'
10.times do |i|
sleep 0.1
input.puts "i => #{i}"
end
input.close
log 'joining output thread'
log Benchmark.measure { output_thread.join }
log 'done'
end
def log(text)
puts "[#{Thread.current.object_id}] #{text}"
end
# `cat` handles streaming correctly
log 'Running `cat`...'
Open3.popen2('cat', &lamb)
puts
log 'Running `sed`...'
# `sed` waits for end of input :/
Open3.popen2('sed', '-e', 's/i/eye/', &lamb)
@ddrscott
Copy link
Author

Uploaded to repl.it: https://repl.it/JpHZ/0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment