0

Currently, I'm writing a Bash program that runs a program with different parameters based on a condition which changes over time, and exits when a key is pressed by the user. It is run with sudo, if that matters. However, read does not seem to be receiving any characters, and the script continues to run. Why does this occur, and how can I fix it? An example of what I'm trying:

(
  read -sN1
  exit
) &
while true; do
  command param1 &
  pid=$!
  while condition; do true; done
  kill $pid
  command param2 &
  pid=$!
  until condition; do true; done
  kill $pid
done
LegionMammal978
  • 680
  • 8
  • 15

1 Answers1

0

One way is to put the outer while loop in the background and kill it after the user presses a key:

while true; do
  pid1=$!
  echo $pid1 > /tmp/pid1
  while condition; do sleep 1; done
  kill $pid1
  wait $pid1 2>/dev/null

  command param2 &
  pid2=$!
  echo $pid2 > /tmp/pid2
  until condition; do sleep 1; done
  kill $pid2
  wait $pid2 2>/dev/null

  sleep 1
done &
pid3=$!

read -sN1
killlist="$pid3 `pgrep -F /tmp/pid1` `pgrep -F /tmp/pid2`"
kill $killlist
wait $pid3 2>/dev/null
rm -f /tmp/pid1 /tmp/pid2

I added some sleep commands so that the potentially infinite while loops don't thrash the CPU.

I added killing of the first and second process after the keypress. $pid1 and $pid2 won't be set for the script's shell, only for the outer loop's subshell, so their values need to be passed by tmp file.

I added wait commands to suppress the output of the kills (https://stackoverflow.com/a/5722874/1563960).

I used pgrep -F to only kill pids from the tmp files if they are still running.

Community
  • 1
  • 1
webb
  • 4,180
  • 1
  • 17
  • 26