Hi, I have a bash function that is called must be called by an EXIT trap after the first time that it is called. The function sets the trap again to fire as soon as the function exits.
echo 0 > .i
function launchNextExperiment
{
( # Run in nested subshell
# Implement a mutex lock, not shown
j=`cat .i`
if [ $j -lt $k ]
then
trap launchNextExperiment EXIT # set trap for this nested subshell
./doStuff &
let j=j+1
echo $j > .i # variables are not known in outer shell, therefore use
# the file .i as a counter
fi
wait # wait for doStuff to return from background before exiting
# from this nested shell and causing an EXIT signal
)
}
launchNextExperiment &
The problem that I have is that the trap is only fired once, in other words doStuff
is only executed twice.
The reason why I am not using a simple for loop to do doStuff
k
times is that I actually call the launchNextExperiment
function once for each of a subset of my CPUs, and only want one instance of doStuff
to run on a CPU at a time since it is very processing intensive. That is also why I have a mutex lock. Then as soon as an instance of doStuff
returns I want to launch the next of the k
instances of doStuff
(in fact they all different simulations).
How can I make sure that the trap is set for every nested subshell, and in the end launchNextExperiment
is executed k
times, but only one doStuff
per CPU?