0

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),
        }
    }
}
mkaito
  • 1,005
  • 1
  • 10
  • 19

1 Answers1

1

When reading from std::io::stdin(), input is buffered until EOF is encountered

Why do you say this? Your code appears to work as you want. If I compile it and run it:

$ ./i
hello
hello

goodbye
goodbye

yeah!
yeah!

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.

Err(_) => timer::sleep(interval)

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:

#!/bin/bash

set -eu

i=0

while true; do
    echo $i
    sleep 1
done

And then ran it:

./bar | ./i
0

0

0

Your program continues to work.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Given a function `bar` that runs `echo bar` every second forever, I'm testing this with `bar | thingy`. It won't print anything until I `^C`. It should really only terminate on EOF. Can I test specifically for EOF in the match? For everything else, it should just retry. – mkaito Dec 14 '14 at 22:20
  • 2
    This is... interesting. `echo` is a builtin in fish, that seems to behave differently in this regard, causing some sort of buffering issue. I've tested again with bash scripts and functions, which work just fine. Well, TIL. Fish is fancy and special. Thanks, Shepmaster! – mkaito Dec 14 '14 at 22:42
  • "[fish] seems to behave differently in this regard" - sounds like another question for SO! ^_^ – Shepmaster Dec 14 '14 at 22:45
  • I still have to post that one about checking specifically for EOF from `read_line()` too. Work to do, work to do! – mkaito Dec 14 '14 at 22:46