bug-bash
[Top][All Lists]
Advanced

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

Re: Why does a Bash shell script write prompts followed by reads and do


From: Eric Blake
Subject: Re: Why does a Bash shell script write prompts followed by reads and do it right?
Date: Wed, 2 Sep 2015 14:55:25 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Thunderbird/38.1.0

On 09/02/2015 02:22 PM, Bob Proulx wrote:
> Robert Parker wrote:
>>         fputs(shortprompt, stdout);
>>         fflush(stdin);
> 
> Uhm...  fflush'ing stdin?  That doesn't make sense.

There is one case where fflush(stdin) is useful on a terminal: it lets
you discard any pending input.  For example, if you have just prompted
for a password and altered the tty to not echo what is typed, then
flushing stdin prior to reading the password is a nice step to ensure
that any accidental type-ahead data entered before the prompt doesn't
get mixed up with the password attempt, particularly since the lack of
echoing won't show the user that the password got munged.

Additionally, fflush(stdin) on a regular file is useful for applications
that might be used in a sequence of processes, and which have scenarios
where they only partially consuming input; POSIX requires that such
applications should reset the file pointer to the last byte actually
processed so that the next process starts processing at the next byte
rather than skipping ahead by however many bytes were cached early but
left unprocessed.  Example: { sed -n 1q; cat; } < file | ... - for the
'cat' to pass the remaining lines to the rest of the pipeline, the 'sed'
must rewind back to the end of the first line even if it read more than
that.

But in most coding scenarios, flushing stdin is rather rare; it wasn't
even well-specified by POSIX until 2012.

>  Obviously you
> meant to flush stdout.

And in the code snippet shown here, this observation is certainly correct.

-- 
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

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