我正在try 用Rust编写一个程序,将字符串写入一个命名的管道.然而,数据只在程序退出后才会显示在接收端.
下面是我的代码:
use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use std::io::Write;
use std::fs::{File, OpenOptions};
fn send_data(file: &mut File, payload: &str) -> Result<(), std::io::Error> {
file.write(payload.as_bytes()).unwrap();
// I tried file.write_all() and file.flush(); same result
Ok(())
}
fn main() {
let mut file = OpenOptions::new()
.write(true)
.open("/tmp/my_named_pipe")
.expect("Failed to open named pipe for writing");
let mut stdout = std::io::stdout().into_raw_mode().unwrap();
stdout.flush().unwrap();
loop {
let key = match std::io::stdin().keys().next() {
Some(Ok(input)) => input,
_ => break,
};
match key { // press x to send data, q to quit
Key::Char('q') => break,
Key::Char('x') => send_data(&mut file, "foobar").unwrap(),
_ => (),
}
}
}
我正在创建一个带有mkfifo /tmp/my_named_pipe
的命名管道,然后用tail -f /tmp/my_named_pipe
开始监听它.然后,在另一个终端窗口中,我运行我的程序(并按下"x"几次)."尾—f"什么都没显示.当我退出我的程序(通过按'q')所有字符串显示一次.
我希望每个按键都能调用send_data()
,每个调用都能立即在tail -f
侧呈现.如何做到这一点?