I feel that i am missing something obvious but i can't find what is wrong.
I have a script that is launching some functions with "&" and each call is feeding the array with a value. When all calls are finished I just want to retrieve the values of that array.
It is looking like that :
#!/user/bin/ksh
#Function called with &
fct()
{
sleep $1
tab_track[$1]="$(date)"
}
#Main
for OneIteration in 1 2 3 4 5
do
fct $OneIteration &
done
wait
echo "Display time"
for OneLine in "${tab_track[@]}"
do
echo ${OneLine}
done
If you wanted to do multiple commands at once and save their results in order, you must first save them separately, because once they're in the background they'll run in no particular order at all.
#Function called with &
fct()
{
sleep $1
date
}
for X in 1 2 3 4 5
do
fct > /tmp/$$-$X &
done
wait # Let them all finish
# Set the array
set -a ARR `cat /tmp/$$-*`
# Remove temp files
rm -f /tmp/$$-*
I am not trying to get the results in particular order but I need to retrieve all of them I was not considering the use temporary file but it seems the way to go. Thanks for pointing me to the right directions.
Yes, each bg proc needs its own output file or pipe, unless you can ensure they write() blocks of whole lines. I had to clean up some shared logs in C/C++, using setvbuf() to make the log's FILE* buffer big, and fflush() to ship each buffered message in a single write(). In shell, you might have problems ensuring atomic line write(). If you want sorted outputsort can be a buffer: