0

I currently try to start background process with coproc and update a name reference variable. My not working code:

function updateVariable(){
  local -n myVar="${1}"
  #i=0;
  while :
  do
    sleep 1
    myVar="ok"
    #((++i))
  done
}

capture=""; coproc mycoproc { updateVariable capture; }

This does not work as I exspected. echo $capture is just empty. I would exspect it to be "ok".

Thanks a lot!

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
kon
  • 113
  • 5
  • 3
    A *co-process* as its name suggests runs in a different process, so whatever modifications you make to variables in that other process won't affect the variable of the main shell process, you'd need to define a protocol for transmitting that variable (co-processes come two pipes one for input one for output for communication). If you want a variable that is incremented every second, look at the `$SECONDS` variable. – Stéphane Chazelas Jul 28 '20 at 12:56
  • I thought "linking" with a name reference variable could allow me to get a connection to the different process. I know it´s possible to communicate using FDs, but I would need to use ```echo``` all the time which means the FD would have many entries than just one single variable. – kon Jul 28 '20 at 13:17
  • By *protocol*, I meant you'd need to send something like `give-me-a-number` to your coproc and read the result back. Shell coprocs are not a very useful feature in general, see [How do you use the command coproc in various shells?](//unix.stackexchange.com/q/86270) about that. – Stéphane Chazelas Jul 28 '20 at 13:31
  • I am not sure if I correctly understand you, but I guess you mean I should perfom some kind of read to always have the latest output saved? My initial idea was using the local -n variable for reading the result back (which under "normal" conditions works just fine). I don´t need to input any number to it. I want to to run always in the background and be able to use the latest result of my background process. – kon Jul 28 '20 at 13:50
  • 1
    A co-process is a different process, you won't get around that. It's intended to run things like servers that take input from the shell and send output back to it. The only communication channels between the processes are those two file descriptors for input/output, there is no magic sharing of variable values between the processes. That coproc shell process will have its `capture` variable, your main shell process will have its own with no relation between the two other than the coproc's one will have initially been copied from the main shell upon forking. – Stéphane Chazelas Jul 28 '20 at 14:41

0 Answers0