Phương Nguyễn
Phương Nguyễn

Reputation: 8905

Using `sleep` makes pipe to not work

I have this oprint script:

#!/usr/bin/env ruby

amount = 100
index = 0
loop do
  index += 1
  if index % 5 == 0
    amount += 10
  end

  sleep 0.1
  $stdout.puts amount
end

If I run oprint | echo, then I don't see anything. If I comment out the sleep 0.1 inside oprint, then I see a lot of output. Does sleep break the pipe? Is there a fix?

Upvotes: 2

Views: 200

Answers (1)

Max
Max

Reputation: 22335

oprint | echo really shouldn't work, because echo doesn't read from the input stream. It echos its arguments. If you want to test a simple pipe, oprint | cat would be more appropriate.

Even then, you should add $stdout.flush after the puts when you have an infinite loop like that. Since lots of small IO calls can be a performance bottleneck, Ruby buffers its output by default - meaning it stores up lots of little output in a buffer and then writes the whole buffer all at once. Flushing the buffer manually ensures that it won't end up waiting forever to do the actual write.

Making those two changes gives me the expected output.

Upvotes: 1

Related Questions