1

I am trying to use a global variable inside two different functions, kind of a shared variable.

Program 1:

#!/bin/bash

glob="1"

func1(){
echo "start1: $glob"
((glob++))
}

func2(){
echo "start2: $glob"
}


func1 
func2

The output is :

 start1: 1 
 start2: 2

This is fine and expected.. Now if i put them in a loop, and send one of the function to background...

 #!/bin/bash

 glob="1"

 func1(){
    echo "start1 :$glob"
     while :; do
        ((glob++))
        echo "Incremneter: $glob" 
        sleep 1
     done   

 }


func2(){
    echo "start2: $glob"
    while :; do
        echo "Receiver $glob "
        sleep 1
    done
}


func1 &
func2

output:

 Incremneter: 3
 Receiver 1 
 Incremneter: 4
 Receiver 1   
 Incremneter: 5
 Receiver 1 
 Incremneter: 6
 Receiver 1 
 Incremneter: 7
 Receiver 1 
 Incremneter: 8
 Receiver 1 
 Incremneter: 9
 Receiver 1 
 Incremneter: 10

and goes on..

The output is such that both the functions are keeping their own copy of the variable "glob". Is this due to the fact that one process is working in the background? Is there a way out, to synchronize the copy of "glob" in both functions.

ArunMKumar
  • 718
  • 2
  • 5
  • 14
  • When you run the function in the background it runs in its own shell process. Variables are copied to the child when you start the function, but lost on return. You need to use either a pipe or return the value and call it as `$( )`. Either way, you won't get multithreading - you can't share variables between bash processes without writing some C (`man shmat`). Even then you have to write synchronisation code - non-trivial. – cdarke Mar 09 '17 at 09:55
  • The 2nd answer in the question I marked as duplicates contains some very useful links (`coprocesses` solves the "shared variable" aspect) – Aserre Mar 09 '17 at 10:00
  • @Aserre I do not see any links, could you post that again.. – ArunMKumar Mar 09 '17 at 13:06
  • @ArunMKumar check the question marked as duplicate of your post – Aserre Mar 09 '17 at 13:16

0 Answers0