help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: weird interaction between builtin cat and trap


From: Jesse Hathaway
Subject: Re: weird interaction between builtin cat and trap
Date: Thu, 14 Apr 2022 10:14:06 -0500

On Thu, Apr 14, 2022 at 9:37 AM Peng Yu <pengyu.ut@gmail.com> wrote:
> This code is the even simpler to reproduce the error.
>
> $ cat ./main.sh
> #!/usr/bin/env bash
> # vim: set noexpandtab tabstop=2:
>
> enable -f "$BASH_LOADABLES_PATH"/cat cat
> trap 'echo EXIT' EXIT
> seq 1000000 | builtin cat | {
>         :
> } {fd}<&0
> $  ./main.sh
> cat: write error: Broken pipe
> EXIT

I think this is a difference in implementation, rather than a bug.
The builtin cat writes any errors to stdout and exits 1, whereas
cat from coreutils sets its exit code to 141 on receiving a
Broken Pipe(32), but does not write anything to stderr.

builtin cat.c:

while (n = read(fd, buf, sizeof (buf))) {
  w = write(1, buf, n);
  if (w != n) {
    e = errno;
    write(2, "cat: write error: ", 18);
    s = strerror(e);
    write(2, s, strlen(s));
    write(2, "\n", 1);
    return 1;
  }
}

This script shows the different behavior:

#!/usr/bin/bash
printf 'Coreutils cat\n'
trap 'echo EXIT' EXIT
seq 1000000 | cat | {
:
}
declare -p PIPESTATUS

printf 'builtin cat\n'
enable -f ./cat.so cat
trap 'echo EXIT' EXIT
seq 1000000 | cat | {
:
}
declare -p PIPESTATUS

$ ~/test.sh
Coreutils cat
declare -a PIPESTATUS=([0]="141" [1]="141" [2]="0")
builtin cat
cat: write error: Broken pipe
declare -a PIPESTATUS=([0]="141" [1]="1" [2]="0")
EXIT



reply via email to

[Prev in Thread] Current Thread [Next in Thread]