From: Szymon Rozga Date: 2007-11-10T01:15:01+09:00 Subject: Re: background process readling lines and responding Alexy, The first thing that comes to mind is that you are writing the sent text to the pipe and then immediately calling readlines; is that enough time for grep to process its work and write the result back to the pipe? Also, by "but it swallows the first line of input and doesn't respond!", do you mean that you are not able to write anymore text (indicating that readlines might be blocking) or just that it never shows grep's result? -Szymon On Nov 9, 6:45 am, Alexy Khrabrov wrote: > Greetings -- I'm debugging a way to call a command-line executable as a > server. In normal life it behaves like grep, reading lines from stdin > and printing responses to stdout. So I'm debugging the Ruby wrapper on > grep, as the original takes a long time to load (thus the whole > exercise). Here's what I got -- but it swallows the first line of input > and doesn't respond! Why? > > #!/usr/bin/env ruby > > require 'optparse' > require 'ostruct' > > class Server > > def initialize(cmd_line) > puts "starting server with the following command line:" > puts cmd_line > @pipe = IO.popen cmd_line, "r+" > end > > def process(sent) > return nil if sent.nil? or sent =~ /^\s+$/ > > puts "sending: [#{sent}]" > @pipe.write(sent) > > @pipe.readlines > end > end # class > > def main > o = OpenStruct.new > files = OptionParser.new do |opt| > opt.on("-e", "--exe EXE", "server executable basename") { |val| > o.exe = val } > end.parse(*ARGV) > > ps = Server.new(o.exe) > > STDIN.each_line do |line| > out = ps.process(line) > puts out > end > end > > main if $0 == __FILE__ > > -- Here's what happens when I try to use it: > > $ aha-grep-server.rb -e "grep abra" > starting server with the following command line: > grep abra > abracadabra > sending: [abracadabra > ] > > -- then it just hangs there, @pipe.readlines returning nothing. What's > the right IO semantics here? > > Cheers, > Alexy > -- > Posted viahttp://www.ruby-forum.com/.