Skip to content

sed - -u does not flush w output files after each line #657

Open

Description

@sylvestre

With -u/--unbuffered, GNU sed flushes the files written by w, W and s///w after every
line, as well as standard output. uutils sed flushes standard output only; w files stay in an
8 KiB buffer until it fills or sed exits. So tail -f log | sed -u -n '/ERR/w errors' leaves
errors empty for a long time, and loses the buffered lines if sed is killed.

Reproduction

The producer writes two lines and then stays open for one second; the file size is checked
after half a second.

Rust (incorrect)

$ ( printf 'ERR1\nok\n'; sleep 1 ) | ./target/release/sed -u -n '/ERR/w r.txt' &
$ sleep 0.5; wc -c < r.txt
0
# (5 bytes once sed exits) Exit code: 0

GNU (correct)

$ ( printf 'ERR1\nok\n'; sleep 1 ) | /usr/bin/sed -u -n '/ERR/w g.txt' &
$ sleep 0.5; wc -c < g.txt
5
# Exit code: 0

Root cause

write_chunk in src/sed/processor.rs:176-188 flushes standard output when
context.unbuffered is set, but nothing flushes the named writers until
named_writer::flush_all() at the end of process_all_files (src/sed/processor.rs:1026):

fn write_chunk(output: &mut OutputBuffer, context: &ProcessingContext, chunk: &IOChunk)
    -> std::io::Result<()> {
    output.write_chunk(chunk)?;
    if context.unbuffered {
        output.flush()?;
    }
    Ok(())
}

NamedWriter (src/sed/named_writer.rs) wraps its file in a BufWriter.

Test

A test needs to observe the file while sed is still running, which is awkward with uutests.
A simpler check is a unit test in named_writer.rs/processor.rs, or an integration test that
kills sed after the first line, e.g.:

#[test]
#[cfg(unix)]
fn test_unbuffered_flushes_w_file() {
    let temp_dir = assert_fs::TempDir::new().unwrap();
    let out = temp_dir.child("out");
    let mut child = new_ucmd!()
        .args(&["-u", "-n", &format!("w {}", out.path().display())])
        .set_stdin(std::process::Stdio::piped())
        .run_no_wait();
    child.write_in("first\n");
    std::thread::sleep(std::time::Duration::from_millis(300));
    assert_eq!(std::fs::read_to_string(out.path()).unwrap(), "first\n");
    child.kill();
}

(Adapt to the UChild API available in the pinned uutests version.)

Reported by Anthropic's OSS Scanner (ANT-2026-IC6SF004).

Activity

  1. added
    bug
    good first issue
    oss-scanner
    gnu-compat
    on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    buggnu-compatgood first issueoss-scanner

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions