Skip to content

Instantly share code, notes, and snippets.

@floere
Created January 8, 2012 09:20
Show Gist options
  • Select an option

  • Save floere/1577817 to your computer and use it in GitHub Desktop.

Select an option

Save floere/1577817 to your computer and use it in GitHub Desktop.
An example of Child/Parent communication.
require 'yajl'
class MasterChild
def initialize
@child, @parent = IO.pipe
start_master_process_thread
end
# This runs a thread that listens to child processes.
#
def start_master_process_thread
# This thread is stopped in the children.
#
Thread.new do
loop do
IO.select([@child], nil, nil, 2) or next
result = @child.gets ';;;'
data = Yajl::Parser.parse result[0..-4]
puts data
end
end
end
def send_to_parent data
close_child
write_parent data
end
# Write the parent.
#
# Note: The ; is the end marker for the message.
#
def write_parent data
@parent.write "#{Yajl::Encoder.encode(data)};;;"
end
# Close the child if it isn't yet closed.
#
def close_child
@child.close unless @child.closed?
end
end
master_child = MasterChild.new
3.times do
fork do
loop do
master_child.send_to_parent "Hello from child with pid #{Process.pid}."
sleep rand*2
end
end
end
loop do
sleep 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment