2017-03-08 82 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脚本。