Vlad the Impala
Vlad the Impala

Reputation: 15882

reading from stdin in one second intervals

I have two simple scripts, reader and writer:

writer.rb:

while true
  puts "hello!"
  $stdout.flush
  sleep 1
end

reader.rb:

while true
  puts "I read: #{$stdin.read}!"
  sleep 1
end

writer.rb continuously writes to stdout, and reader.rb continuously reads from stdin.

Now if I do this:

ruby writer.rb | ruby reader.rb

I would expect this to keep printing

I read: hello!
I read: hello!
I read: hello!

At one second intervals. But it just blocks without printing anything. How do I get it to print? I thought writer.rb was caching the output so I added $stdout.flush, but that didn't get me anywhere.

Upvotes: 3

Views: 154

Answers (2)

Dogbert
Dogbert

Reputation: 222458

You need to use $stdin.gets instead of .read as .read reads till EOF.

puts "I read: #{$stdin.read}!"

should be

puts "I read: #{$stdin.gets}!"

Note: This will include the newline character, so the output will be something like:

I read: hello!
!
I read: hello!
!
I read: hello!
!

If you don't want the trailing newline, use $stdin.gets.chomp

Output with $stdin.gets.chomp:

I read: hello!!
I read: hello!!

Upvotes: 3

themel
themel

Reputation: 8905

I had a quick look at the documentation of read, which states:

If length is omitted or is nil, it reads until EOF

which in your case happens when the writer terminates, which is expected to be never. You might want to use readline.

Upvotes: 2

Related Questions