#!/usr/bin/ruby
require "io/wait"
require 'pp'
rd, wr = IO.pipe
#Process.sync = true
Process.fork do
puts "Sending message to parent"
File.open("/home/alisoft/test.dump") do |f|
f.each do |l|
wr << l
#wr.flush
sleep rand(5)
end
end
wr.close
p "Write pipe closed."
end
Process.fork do
sl = ""
loop do
case rd.ready?
when Fixnum
p "Parent got: <#{rd.read(rd.ready?)}>"
when true,false,nil
#false eq rd.eof?
begin
p "Parent got: <#{rd.readpartial(1000)}>"
#这里用read方法的话会产生堵塞,
#用readpartial的话会不知道现有内容的长度。
rescue EOFError
(rd.close;exit(0)) if rd.eof?
end
else
#do nothing
end
p Time.now.to_s
end
end
puts "Main is going down"
pp Process.waitall
puts "Main over"
Ruby有堵塞和非堵塞管道两种实现。
感觉这种通信方式不如Socket,这个虽然快,但Socket更容易扩展,
比如使用内存Cache,只是不能将信号和数据一次就传过来,
1、A先告诉B内存Cache里面有新东西了,去更新吧。
2、B收到,更新了。
用System V的信号也好,32-64之间的信号可自定义,只是数据如何传递还要另想办法。