2017-03-08 86 views
0

我已經創建了一個腳本來編譯然後執行4.c程序。現在Bash腳本 - 如何知道一個程序已經終止

,我的腳本如下:

#!/bin/sh 

echo "Compiling first program. . ." 
gcc -o first first.c 
echo "File compiled." 
echo 

echo "Compiling second program. . ." 
gcc -o second second.c 
echo "File compiled." 
echo 

echo "Compiling third program. . ." 
gcc -o third third.c 
echo "File compiled." 
echo 

echo "Compiling fourth program. . ." 
gcc -o fourth fourth.c 
echo "File compiled." 
echo 

./first 
./second 
./third 
./fourth 

每個可執行文件需要單獨運行。 問題是:以這種方式啓動高管,他們會同時執行嗎?在啓動下列程序之前,我如何知道程序何時終止?

+1

您的示例以序列形式啓動它們。所以,每一個proram都會在完成之前運行。 (除非程序自行分叉)。對於並行執行,您需要將它們發送到背景(使用'&')或使用'gnu parallel'或'xargs -P'等...... – jm666

回答

2

在bash腳本下一個開始前將完成,除非你專門使用功能,確實否則每個命令,如&

foo bar &    # starts `foo bar` to run "in the background" 
         # while the script proceeds 

|

foo | bar    # runs `foo` and `bar` in parallel, with output 
         # from `foo` fed as input into `bar. (This is 
         # called a "pipeline", and is a very important 
         # concept for using Bash and similar shells.) 

那說,這並不意味着該命令成功完成。在你的情況下,你的一些gcc命令可能會失敗,但其他程序仍然可以運行。這可能不是你想要的。我建議爲每個命令添加如|| { echo "Command failed." >&2 ; exit 1 ; },這樣如果它們失敗(意思是說,如果它們返回0以外的退出狀態),那麼腳本將打印一條錯誤消息並退出。例如:

gcc -o first first.c || { echo "Compilation failed." >&2 ; exit 1 ; } 

和:

./second || { echo "Second program failed." >&2 ; exit 1 ; } 

(你也可以把這種邏輯的「功能」,但是這可能是另一天的教訓!)

我建議順便閱讀Bash教程,和/或the Bash Reference Manual,以更好地處理shell腳本。