Input buffer and READ

Hello everyone,
Can someone please explain the input buffer behaviour for the read command in ksh93 on AIX?
I have 'googled' for weeks now, and did not find a satisfactory answer or solution to my dilemma.
I have the following code:

STTY=$(stty -g)
if [ -t 0 ];then 
   stty -echo -icanon time 0 min 0
fi
k=""
while [[ "x$k" = "x" ]];do
read k

# here is a group of command that retrieve data from several files
# and process the data summarizing and filtering it (using awk).
# This section could possibly take 1 to 2 seconds to complete its job
# the final command does a cat of the generated data file to the screen
# then the loop would start again retrieving fresh stats from files....
#  ........
done
stty $STTY

How can I guarantee that the input buffer to the read will keep a key that the user presses while inside the loop execution?
When I execute the code and press any key, sometimes it exits properly, other times it takes more than one key press to exit, maybe because the key got pressed while the processing section of the loop was running.
What could be 'chewing up' the pressed keystroke? Did the input buffer clear?
Do you have suggestions on how to guarantee termination on a single key stroke?
Maybe I need to redesign my loop logic ?
I am open to any advice and suggestion.
Thanks to all!

read is known to alter terminal settings in many shells. To guarantee you're getting a raw read with the terminal characteristics you set, try dd.

k="$(dd count=1)"

Also note that some keypresses may be more than one byte of output.

1 Like