0
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thread|
    stdout.sync = true;
 
Thread.new do
   stdout.each.with_index {|line, line_no| updateParameters(line) if line_no == $lineStartIndex}
 end

 stdin.puts "e #{$initialState}"

 stdin.puts "e #{$nextState}"
 
 stdin.puts "e #{$nextState}"

 stdin.close

 wait_thread.value
end

In the following code, I want to read the data from stdout after each stdin. My next input depends on what I get in the last output. I want to call updateParameters() function to update the nextstate which will be used for the next input. But currently I get the output only after the input process is complete. Hence nextState is not getting updated and I'm getting wrong output.

I understand that currently all the data is stored by ruby in bufffer and the entire output is returned after receiving all the inputs.

But is there a way to read the output here after each input command?

  • I don't think your code does what you expect. While `$stdout.sync` may avoid buffering, you're not reading it within the right thread. I could be wrong, but I think you need to read from *stdout* within each thread, or ensure you call [stdout.flush](https://stackoverflow.com/q/39920517/1301972) explicitly. *See also: [IO#flush](https://ruby-doc.org/core-3.0.3/IO.html#method-i-flush)* – Todd A. Jacobs Nov 27 '21 at 22:11
  • @ToddA.Jacobs Actually you can read the data within the thread only after all the input commands has been executed and then stdin closes after which it jumps to the code defined under thread. – anjali ahlawat Nov 28 '21 at 12:02

0 Answers0