繁体   English   中英

如何在陷阱代码中再次设置bash陷阱?

[英]How to set bash trap again in trap code?

我有一个bash函数,它必须在第一次调用后由EXIT陷阱调用。 该函数将在退出时立即将陷阱重新设置为触发。

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 &

我的问题是陷阱仅触发一次,也就是说doStuff仅执行两次。

我之所以不使用简单的for循环执行doStuff k次,是因为我实际上为我的每个CPU子集调用一次launchNextExperiment函数,并且只希望一次doStuff实例一次在CPU上运行这是非常密集的处理。 这就是为什么我有一个互斥锁。 然后,一旦doStuff实例返回,我就想启动doStuffk实例中的下一个(实际上,它们都是不同的模拟)。

我如何确保为每个嵌套的子shell设置陷阱,最后将launchNextExperiment执行k次,但每个CPU只有一个doStuff

不是您问题的答案,但是您可以尝试完成的工作没有陷阱和子shell:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM