用 rust 执行“tail -f xxx”

问题描述 投票:0回答:2

我想用 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

rust command tail
2个回答
2
投票

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


0
投票

跑步:

$ cargo test -- --nocapture

#[cfg(test)]
mod tests {
    use std::io::BufRead;
    use std::io::BufReader;
    use std::process::{Command, Stdio};
    #[test]
    fn test_stdout() {
        let cmd = Command::new("./slow_output_stream")
            .stdout(Stdio::piped())
            .spawn()
            .expect("command failed");
        let mut out = cmd.stdout.unwrap();

        loop {
            let mut reader = BufReader::new(&mut out);
            let mut line = String::new();
            let num_bytes = reader.read_line(&mut line).unwrap();
            if num_bytes == 0 {
                println!("End of stream.");
                break;
            }
            println!("The line: {:?}", line);
        }
        println!("Done.");
    }
}

额外的功劳,这是 Rust 中的一个缓慢的输出流,只需构建它并复制二进制文件到其他程序可以找到它的地方:

use std::{thread, time};

fn print_row(row: &Vec<i32>) -> () {
    let wait_time = time::Duration::from_secs(2);

    row.iter().for_each(|int| {
        println!("{}", int);
        thread::sleep(wait_time);
    });
}

fn main() {
    let matrix = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];

    matrix.iter().for_each(print_row);
}
© www.soinside.com 2019 - 2024. All rights reserved.