exec "tail -f xxx" 生锈

exec "tail -f xxx" with rust

我想用 rust 执行 tail -f a,但是当我 运行 以下代码时没有输出:

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);
}

当我向文件 a 添加一个新行时,我只得到 tail: a: file truncated.

read_to_string 读取直到 EOF,永远不会被击中,因为 tail 连续输出并且永不结束。将您的程序更改为一次读取和打印一行。