accessing variable from while loop

Hi all,

Here is an outline of the problem:

#variable declared at start of script
x=0;

#a function that increments x by 1 every 10 seconds
incrementX(){
increments x every 10 seconds;
}

#i want this to output the value of x every second. The problem is that x is always reported as 0. This is in spite of the fact that x actually is updated as is known from other functions in the script. 
globalTimer(){
while true; do
sleep 1
echo $x;
done
}

#run both functions
incrementX &
globalTimer

Hi that will not work, since incrementX gets run in a sub shell, the value of x in that particular shell will remain unknown to the parent shell.

You will need to change the structure of the program to have a main loop to incorporate both timers, or use a sort of inter-process communication. One way would be to send a signal to the parent shell. Another would be a named fifo. Since we are just incrementing a number, we can use the simple signaling.

#!/bin/bash

#variable declared at start of script
x=0;

#a function that increments x by 1 every 10 seconds
incrementX() {
        local ppid=$1

        while true; do
                sleep 10
                kill -USR1 "$ppid"
        done
}

globalTimer() {
        while true; do
                sleep 1
                echo $x
        done
}

#increment x on signal from async timer
trap 'let x++' SIGUSR1
#kill children when we exit
trap 'kill 0' EXIT

#run both functions
incrementX $$ &
globalTimer

Thanks buddy. I'll have a look at that over the weekend.