2010-05-07 58 views
17

我有一個C shell腳本,做這樣的事情:如何在shell腳本中使用並行執行?

#!/bin/csh 
gcc example.c -o ex 
gcc combine.c -o combine 
ex file1 r1  <-- 1 
ex file2 r2  <-- 2 
ex file3 r3  <-- 3 
#... many more like the above 
combine r1 r2 r3 final 
\rm r1 r2 r3 

有一些辦法可以讓線12並行而不是一個接另一個3運行?

回答

13

將其轉換爲具有適當依賴關係的Makefile。然後你可以使用make -j讓並行運行一切。

請注意,Makefile中的所有縮進必須是纔是TAB。 TAB顯示要運行的命令的位置。

另請注意,此Makefile現在使用GNU Make擴展(通配符和子功能)。

這可能是這樣的:

export PATH := .:${PATH} 

FILES=$(wildcard file*) 
RFILES=$(subst file,r,${FILES}) 

final: combine ${RFILES} 
    combine ${RFILES} final 
    rm ${RFILES} 

ex: example.c 

combine: combine.c 

r%: file% ex 
    ex $< [email protected] 
+0

您的'-l combine'應該是'-o combine' – SiegeX 2010-05-07 19:39:38

+0

您是否會首先使用'final'規則使其成爲默認? – 2010-05-07 19:41:11

+0

我在想什麼?固定。 – 2010-05-07 23:06:35

7

在bash,我會做;

ex file1 r1 & 
ex file2 r2 & 
ex file3 r3 & 
wait 
... continue with script... 

併產生它們並行運行。另一個例子可以是check out this SO thread

4
#!/bin/bash 

gcc example.c -o ex 
gcc combine.c -o combine 

# Call 'ex' 3 times in "parallel" 
for i in {1..3}; do 
    ex file${i} r${i} & 
done 

#Wait for all background processes to finish 
wait 

# Combine & remove 
combine r1 r2 r3 final 
rm r1 r2 r3 

我稍微改變的代碼使用括號展開{1..3},而不是硬編碼的數字,因爲我只是意識到,你說有很多不僅僅是3.括號擴展更多的文件使得擴展到更大的數字瑣碎通過更換「 3'在大括號內,以任意數量您需要。

1

可以使用 CMD & 和等待後

 
#!/bin/csh 
echo start 
sleep 1 & 
sleep 1 & 
sleep 1 & 
wait 
echo ok 

測試:

 
$ time ./csh.sh 
start 
[1] 11535 
[2] 11536 
[3] 11537 
[3] Done     sleep 1 
[2] - Done     sleep 1 
[1] + Done     sleep 1 
ok 

real 0m1.008s 
user 0m0.004s 
sys 0m0.008s 
0

GNU並行會讓它非常喜歡:

seq 1 3 | parallel ex file{} r{} 

取決於如何「恩'和'結合'你甚至可以做的工作:

seq 1 3 | parallel ex file{} | combine 

瞭解更多關於GNU並行觀看http://www.youtube.com/watch?v=LlXDtd_pRaY

1

你可以使用nohup例如:

nohup ex file1 r1 &  
nohup ex file2 r2 & 
nohup ex file3 r3 & 
0

xargs可以做到這一點:

seq 1 3 | xargs -n 1 -P 0 -I % ex file% r%

-n 1用於「每行輸入一行」,-P用於「並行運行每行」