我有一个被调用的bash函数,它必须在第一次被调用后被出口陷阱调用。该函数再次将陷阱设置为在该函数退出时立即触发。
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只执行两次。
我之所以不使用简单的doStuff循环来执行k时间,是因为我实际上为我的CPU子集中的每一个调用了一次launchNextExperiment函数,并且一次只希望doStuff的一个实例在一个CPU上运行,因为它是非常处理密集型的。这也是我有一个互斥锁的原因。然后,一旦doStuff的一个实例返回,我就想启动doStuff的下一个k实例(实际上,它们都是不同的模拟)。
如何确保为每个嵌套子外壳设置陷阱,并最终执行launchNextExperiment k次,但每个doStuff只执行一次?
发布于 2010-11-14 10:34:33
这不是你的问题的答案,但是你想要完成的事情可以在没有陷阱和subshell的情况下完成:
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 &
donehttps://stackoverflow.com/questions/3890646
复制相似问题