Strange echo behaviour

Denys Vlasenko vda.linux at
Thu Jan 27 09:11:22 UTC 2011

On Thu, Jan 27, 2011 at 6:48 AM, Rich Felker <dalias at> wrote:
>> > Looking into the code it seems like the fflush() call at the end for
>> > echo_main() is somehow responsible for this, but this is only a guess.
>> I would like to make it so that echo doesn't retry failed writes
>> (except on EINTR).
>> I wonder how to fix this, though. I can easily detect write error,
>> but how to discard buffered data in a FILE object?
>> Even without fflush(), libc will try to write it out at fclose()!
> Are you sure? My impression was that after error, the FILE enters an
> error state, the buffer is invalidated, and no further IO will be
> attempted unless clearerr is called. I suspect libcs could differ in
> this regard...
> One way to prevent further writes reliably is:
> tmp=open("/dev/null", O_RDONLY);
> dup2(tmp, fileno(f));
> close(tmp);

This clobbers the descriptor. echo_main() is called by shell code
directly. So, this shell fragment:

echo qwerty   # assume we get write error here
echo asdfgh
exec 2>&1

will exhibit two bugs: $err will be 0 and fd 2 will be dup'ed
to a wrong fd.


More information about the busybox mailing list