When reading from std::io::stdin()
, input is buffered until EOF
is encountered. I'd like to process lines as they arrive, rather than waiting for everything to be buffered.
Given a shell function bar
that runs echo bar
every second forever, I'm testing this with bar | thingy
. It won't print anything until I ^C
.
Here's what I'm currently working with:
use std::io;
use std::io::timer;
use std::time::Duration;
fn main() {
let mut reader = io::stdin();
let interval = Duration::milliseconds(1000);
loop {
match reader.read_line() {
Ok(l) => print!("{}", l),
Err(_) => timer::sleep(interval),
}
}
}
Why do you say this? Your code appears to work as you want. If I compile it and run it:
The first of each pair of lines is me typing into the terminal and hitting enter (which is what
read_line
looks for). The second is what your program outputs.This is a bad idea - when input is closed (such as by using
^D
), your program does not terminate.Edit
I created a script
bar
:And then ran it:
Your program continues to work.