linux - stopping the script by pressing the specific button (listen STDIN while script is dealing with it) -


there script interacts user "press y / n" dialog (i.e. stdin in use). pressing predefined keyboard button main script should interrupt work.

i tried implement 2 ways, read , using grep (ah, , tried using stty - stty -echo -icanon time 0 min 0, in didn`t work).

the problem grep (grep -q ) main thread goes in loop grep (which looped in order check stdin), while need main script move on, listening stdin specific key pressed. read transformed such small piece:

breakbybutton() { while ! [ "$z" = "11" ]     read -t 1 -n 1 key      if [[ $key = <desired key> ]]             echo -e "\n\e[31mstopped user\e[0m"         break     fi done } 

of course, function works called. separate script in background, grep, execution interrupted after first pressing enter. i'm thinking of parallel process - script , read, haven`t got decisions yet.

that why there interrupts. if want interrupt process otherwise using stdin, type ctrl-c. interrupts process and, optionally, passes control interrupt handler. example, in script myexit functions interrupts handler. if run script , type ctrl-c, execution stops , desired message appear:

myexit() {     echo -e "\n\e[31mstopped user\e[0m"     exit }     trap myexit int  while true     # important captures stdin     cat >/dev/null done 

in practice, myexit should whatever needed clean after script execution interrupted. includes, example, deleting temporary files.

the key feature of approach works when stdin in use. not require waiting until stdin available.


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -