开发者

How to set bash trap again in trap code?

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, no开发者_Go百科t 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?


Not the answer to your question, but what you're trying to accomplish can be done without traps and subshells:

echo 0>i
k=10
dispatch_work()
{
  mutex_lock
  i=$(<i)
  let i++
  echo $i>i
  mutex_unlock

  if [ $i < $k ]; do
    do_work $i
    dispatch_work
  fi
}

for c in $(seq 1 $cpus); do
  dispatch_work &
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜