I'm confused by the following behavior on Linux.
With the below Rust code, when I run the resulting binary in one terminal and run
cat /tmp/fifotest
in another terminal, then in the latter terminal, I sometimes get one "Hello" line, but most often many "Hello" lines per invocation of cat.
/*
In Cargo.toml:
[dependencies]
nix = { version = "0.31", features = [ "fs" ] }
*/
use nix::{sys::stat::Mode, unistd::mkfifo};
use std::io::Write;
const FIFO_PATH: &str = "/tmp/fifotest";
fn main() {
let _ = mkfifo("/tmp/fifotest", Mode::S_IRWXU);
loop {
if let Ok(mut fh) = std::fs::File::options().write(true).open(FIFO_PATH) {
let res = fh.write_all(b"Hello\n");
if let Err(e) = res {
println!("Error: {e:?}");
}
}
}
}
When I run the binary with strace, I always only get one line when cating the fifo. Also, if I insert a millisecond pause in the end of the loop, I always get exactly one Hello line when cating the fifo. It doesn't matter if I compile the Rust code in debug or release mode.
As far as I know, Rust will close the file handle by the end of the loop, and that should cause the reading cat to exit. Am I misunderstanding something about Rust, or Linux, or both?
How to change the code (without introducing sleeps), so that the receiving cat will only get one line?
This is Arch Linux, kernel 7.1.6, glibc 2.44, Rust 1.97.1.
(More strangeness: In the terminal where the binary runs, I get the following error in a small subset of the times that cat is run, unrelated to the number of lines which cat sees: Error: Os { code: 32, kind: BrokenPipe, message: "Broken pipe" }.)