command & + wait 方式輕鬆搞定shell多進程,下面給出一個小例子。
首先看main.sh,shell腳本的主實現。
function main(){
while true
do
for((i=0;i<5;i++));
do
{
python number.py $i
} &
done
wait
python another.py
done
}
main
這樣就可以開5個進程執行number.py的代碼,5個進程是同時進行的。
5個number.py進程執行完之後,執行another.py的代碼。循環往復,一直執行。
給出number.py和another.py代碼,方便讀者直接拿來測試。
number.py
import sys
import time
number = sys.argv[1]
print(number)
if number == "2":
time.sleep(5)
else:
time.sleep(1)
another.py
import time
print("another")
time.sleep(0.8)
如果main.sh中不使用wait指令,number.py和another.py會同時執行,another.py不會等到之前的5個number.py進程執行完之後再運行。
改動爲以下形式也是有問題的,並不能保證another.py在5個number.py進程執行完之後運,但是another.py的啓動是在5個number.py進程啓動之後才進行啓動的。
function main(){
while true
do
for((i=0;i<4;i++));
do
python number.py $i &
done
python number.py 5
python another.py
done
}
main