I want to create the script which runs function in background, but leaves ability to query that function about results, pause, resume or other way to interact with it.
For simplicity, lets say, i want to run the counter in the background which increases each second. For user interaction i will leave endless loop with read function.
When I enter p
I expect to see current $counter
value.
When I enter q
I expect while
loop in loop_counter
function will stop as I set $RUN
to false
.
#!/bin/bash
RUN=true
counter=0
print_counter() {
echo "Current value is: $counter"
}
loop_counter() {
while $RUN
do
echo $counter >> file
((counter++))
sleep 1
done
}
loop_counter &
while true
do
echo "Print or Quit?"
read x
case $x in
p) print_counter ;;
q) RUN=false; break ;;
*) echo "Use p or q!" ;;
esac
done
wait
I print $counter
value to file
, just to watch on another terminal with tail -f file
When I hit p
I get 0
as $counter
loops in subshell.
When I hit q
script brakes from the while
loop and it wait
s for subprocess in background will stop. Unfortunately it continues as variable $RUN
in function loop_counter
remains true
.
Any ideas how can I read the current value of $counter
or change the value of $RUN
? Is it possible to create something like a socket?
Thanks