From: Robert Klemme Date: 2010-03-02T18:31:19+09:00 Subject: Re: IO.popen with Threads 2010/3/2 Eikichi On : > Thank you very much for your answer, Robert.  Thanks to your help, I > could start coding. But I have another little problem and I would > appreciate your opinion. > > Here is the code I used: > >    class Test >      def initialize(program) >        while isready?(program) && cool?(program) >          program.puts 'start', 'my name is ...' >          # ... >        end >      end > >      protected > >      def process_command(program, command) >        begin >          rdr = Thread.new { program.read } # alternative: io.readlines >          program.puts "#{command}" >          program.close_write >          rdr.value # joins and fetches the result >        end >      end > >      def isready?(program) >        reply = process_command(program, 'isready') >        reply.chomp.match(/yes_i_am_ready$/) >      end > >      def cool?(program) >        reply = process_command(program, 'cool') >        reply.chomp.match(/yes_i_am_cool$/) >      end >    end > > program = IO.popen("./program", "w+") > > a = Test.new(program) > (...)in `write': not opened for writing (IOError) > > As we can see, there is an error when I try to send a message to the > sub-process because of the closure of the stream > (http://ruby-doc.org/core/classes/IO.html#M002289). > > I believe that it is not possible to open again a closed stream. Exactly that is the source of your error. >  Do you > think a good way is to don't close the stream (except at the very end of > the Ruby script)? or should it be better to change the current code > structure? I would certainly change the structure. I would put the IO.popen inside the class since you will be writing a class handling a specific external program - at least that's what seems to be the case here. When you close the stream depends on the external program you are executing. There is no general rule I can give you here. Note that if you need to deal with multiple requests and responses from the external process I believe there are a number of tools around for that already. You should be able to find something by searching for "ruby expect". Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/