rustcommandtail

exec "tail -f xxx" with rust


I want to exec tail -f a with rust, but there is no output when I run following code:

fn main() {
    // "a" is a text file and some characters have been written to it
    let child = Command::new("tail").args(&["-f", "a"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn().expect("failed tail command");
    let mut s = String::new();
    child.stdout.expect("error of stdout")
        .read_to_string(&mut s).expect("error of read all");
    println!("{}", s);
}

When I append a new line to file a I just get tail: a: file truncated.


Solution

  • read_to_string reads until EOF, which will never be hit since tail outputs continuously and never ends. Change your program to read and print a line at a time.