Named pipes are an old trick for Unix types to accomplish communication between processes. I've actually never used the trick and it took me a little time to figure out how to do this in ruby. In this post I present a quick example for your enjoyment.
First, in a terminal window create the named pipe:
mkfifo my_pipe
At that point it looks like a file on the file system. It even has permissions on it. Now in Ruby processes we can open it like a file:
output = open("my_pipe", "w+") # the w+ means we don't block
output.puts "hello world"
output.flush # do this when we're done writing data
And here we are in a completely separate process:
input = open("my_pipe", "r+") # the r+ means we don't block
puts input.gets # will block if there's nothing in the pipe
If you pair that up with JSON, you've got a quick and efficient way to do inter-process communication. I'm actually using this trick so I can have my Sinatra web service call out to C++, Java, and Python processes.
Broken in JRuby.
http://jira.codehaus.org/browse/JRUBY-3877
Posted by: Matthew King | August 24, 2010 at 12:12 PM