Created
September 23, 2011 23:49
-
-
Save ak47/1238735 to your computer and use it in GitHub Desktop.
multi-process, multi-pipes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'awesome_print' | |
read_pipes = Array.new | |
3.times do |index| | |
parent_read, child_write = IO.pipe | |
read_pipes << parent_read | |
fork do | |
begin | |
sleep 2*index | |
child_write.puts rand(99)*index | |
ensure | |
child_write.close | |
end | |
end | |
end | |
puts 'forking done' | |
File.open('out','w'){|x| x.puts ''} | |
threads = [] | |
read_pipes.each do |pipe| | |
threads << Thread.new do | |
while true | |
result = IO.select([pipe],nil,nil,0.001) | |
next if result.nil? | |
c = pipe.gets | |
break if c.nil? | |
ap c | |
out_file = File.open('out','a') | |
out_file << c | |
out_file.close | |
end | |
end | |
end | |
threads.each { |aThread| aThread.join } | |
puts 'waiting done' | |
puts File.open('out').read |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment