I am having a script which I run in zsh. Upon invoking the script, it runs the main_process() function. The main_process requires ${hash_from_evaluator} for rest of its operation, however calculating this value takes time.
To speed things up, I first invoke 5 _evaluator() as sub-processes in the background, which can run independently and parallel, to find out some value of ${hash_from_evaluator}.
main_process() can operate with any value of $hash_from_evaluator as long as it matches a given regex. Any sub-process which first returns this value can be taken, and then remaining sub-processes must then be killed.
I request for your kind help please. I am able to launch the sub-processes, however, unable to monitor if any one of them has returned the value, then use the value and kill rest sub-processes. How do I do this in zsh?
#!/usr/bin/env zsh
zmodload zsh/system
_evaluator(){
printf "launched subprocess $1 with PID $sysparams[pid]"
while ! [[ ${hash_from_evaluator} =~ ${input_regex} ]]; do
hash_from_evaluator="custom commands to maniuplace some data and get some hash as result"
done
return_value="subprocess $1 calculated ${hash_from_evaluator}"
echo ${return_value}
}
main_process(){
local input_regex="^abc123"
local hash_from_evaluator=""
for i in {1..5}; do
echo "starting subprocess $i"
_evaluator $i &
pids[$i]=$!
done
# Requesting for yout kind help here please
# wait for any one of the 5 subprocesses to give back $return_value.
# assign this $return_value to hash_from_evaluator.
# kill other 4 child processes.
.... rest of the script consumes any valid ${hash_from_evaluator} in match with $input_regex
}
main_process "$@"