[solved] How to block on receiving data from a pipe?



I am very new to Rust and I am currently trying to implement a simple program that get its data from a pipe.

The program description is the following:

  1. connect a program (A) that outputs data to my rust program ® using a pipe: A | R.
  2. the program ® should consume the data line by line as they come.

I have written this simple code for now:

use std::io;

fn main() {
    let mut count = 0;
    loop {
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("failed to read from pipe");
        println!("in: {}", input);
        if count > 5 {
        count += 1;

Unfortunately this program doesn’t wait for the data and loops over and over:

in: hello

in: world


Is there a way to make it block on receiving the data from the pipe? Something like a TCP stream listen().



Actually the code is working fine as is. It can be tested by using cat | thisprogram.

The reason why there are empty in: is because the program A was only outputting 2 lines and then quitting.


Note that the standard way to “stop” these kinds of loops is to quit when you get to EOF (conventionally, a zero sized read). In particular, read_line returns the number of bytes read, which is thrown away in your code. There’s an example looping over lines here: https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line