2010-10-08 130 views
1

我有一個調用的bash函數必須在第一次被調用後由EXIT陷阱調用。該函數在陷阱函數退出後立即再次設置陷阱。如何在陷阱代碼中再次設置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只執行了兩次。

爲什麼我不能用一個簡單的循環來doStuffk倍的原因是,我竟然叫launchNextExperiment函數一次我的每個CPU的一個子集,而只想要doStuff一個實例,一個CPU上運行因爲它的處理密集程度很高。這也是爲什麼我有一個互斥鎖。然後,只要doStuff的實例返回,我想要啓動 doStuff(實際上它們都是不同的模擬)的下一個k實例。

如何確保陷阱設置爲每個嵌套的子shell,並且最後launchNextExperiment執行的是k次,但每個CPU只執行一次doStuff

+0

出口俘獲是清理任務,而不是爲程序邏輯。 – ceving 2017-04-12 11:03:27

回答

0

不回答你的問題,但你要完成,而不陷阱和子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