0

I hava a main shell, during its running, I need to call a function (update_bk) in the background. the purpose of this function is to update a variable (VarA) which will be used by main shell later. I know if I call update_bk function in background, it would be run as subshell, so that the update to the value of VarA by update_bk can not be seen from main shell. therefore, I use mkpipo to solve the problem in update_bk function.

the update_bk function is

update_bk(){

    local VarB
    
    mkfifo ${update_bg_fifo}
    
    until [[ Condition  ]]
    do
        VarB=$(otherFunction)   
        sleep 5
    done
    
    echo ${VarB} > ${update_bg_fifo} && rm ${update_bg_fifo}

}

the main bash shell is

Until [condition]
do
[condition 1] to check if ${update_bg_fifo} is ready, and cat it to the VarA
some thing job2
[condition 3] && [ ! -P ${update_bg_fifo} ] to do call (update_bk) $   (when contion3 is true and no existing update_bk is running)
done

My quesition is how to code the [condition 1] in main shell, to check if ${update_bg_fifo} is ready to cat. I am now using [-p ${update_bg_fifo}] as the condition ,but cat ${update_bg_fifo} is keep wating update_bk() finishes to write ${update_bg_fifo}.

Jetchisel
  • 7,493
  • 2
  • 19
  • 18
seanlv
  • 13
  • 3

1 Answers1

0

you can use stdout instead fifo. call the function and write output into variable

update_bk(){
  local VarB
  ...
  echo "$VarB"
}

update_bg=$(update_bk)
echo "$update_bg"
alecxs
  • 701
  • 8
  • 17
  • thanks alexs, but it's not acceptable, because the update_bg=$(update_bk) need severel minutes to get the updated value, and main sheel can not wait, so that I would like to put it in the background. – seanlv Dec 27 '22 at 02:34
  • if main is intended to process result of sub it must wait regardless it's running in background (you can send to background with `&` so that line is non-blocking) – alecxs Dec 27 '22 at 12:23
  • background mains a way of subshell. Unfortunately, the updated value can not be known for the main shell. – seanlv Jan 03 '23 at 16:41