MAX_READ = 4
rd, wd = IO.pipe
pid = fork do
wd.close
msg_buffer = ""
c = 0
while( 1 )
# select on the read end of the pipe
ready = IO.select( [rd], nil, nil, 1 )
if ready
ready[0].each do|io|
msg_buffer << begin
io.read_nonblock(MAX_READ)
rescue EOFError
puts "the pipe was unexpectidly closed??"
exit
rescue Object => e
STDERR.puts "failed with" + e.message + "\n" + e.backtrace("\n")
end
last_is_complete = msg_buffer.match(/\n\n$/)
messages = msg_buffer.split("\n\n")
# the last msg is not complete
if !last_is_complete
msg_buffer = messages.pop
else
msg_buffer = "" # reset the msg_buffer we're reading everything
end
messages.each do|msg|
puts msg
c += 1
end
puts c
end
end
end
end
rd.close
count = 10
while( count > 0 )
wd.write( "hello\n\nhello\n\nhello\n\n" )
wd.write( "hello\n\n" )
wd.write( "hello\n\nhello\n\nhello\n\n" )
wd.write( "hello\n\n" )
wd.write( "hello\n\n" )
sleep 0.1
count -= 1
end
wd.close
IO.pipe for interprocess communication
Monday, November 19, 2007
IO.pipe for interprocess communication
Pipes are a really simple way to send messages from one process to another.
Subscribe to:
Post Comments (Atom)

0 comments:
Post a Comment