首页 > 解决方案 > 当另一个以 bash 结束时运行并行进程

问题描述

当我必须从 bash 运行六个 python 脚本时,我有一个任务。我有三个短脚本(拍照)和三个长脚本(图像处理),应该在照片完成后运行。

我知道要让两个进程串联运行,我应该写

python script1.py
python script2.py

并进行并行执行我应该写

python script1.py & python script2.py

但是我怎样才能实现这样的目标:

在此处输入图像描述

第 2 和第 3 个进程并行运行,在第 1 个之后,

当 2 完成时,第 4 和第 5 次并行运行(第 3 次仍处于活动状态)

第 4 次完成后第 6 次运行(第 3 次和第 5 次仍然有效)

标签: bashparallel-processing

解决方案


您可以附加&到命令以在后台运行它,并使用wait内置命令等待后台作业完成。

因此,如果您以适当的顺序运行脚本,运行那些没有其他进程依赖于它们的脚本首先在后台完成,然后在最后等待所有脚本,那么这两件事的组合将满足您的需求背景的完成。

#!/usr/bin/env bash

demo() {
    echo "$1 starting for $2 seconds"
    sleep "$2"
    echo "$1 done"
}

echo "Begin Demonstration"

# Process 1 runs in the foreground.
demo 1 2
# Now run 3 in the background after 1 finishes.
demo 3 10 &
# And 2 in the foreground.
demo 2 2
# Now run 5 in the background after 2 finishes.
demo 5 10 &
# And 4 in the foreground.
demo 4 2
# Finally run 6 after 4 finishes.
demo 6 10
# Wait for any still running jobs to finish.
wait

echo "End Demonstration"

运行此脚本将输出:

Begin Demonstration
1 starting for 2 seconds
1 done
2 starting for 2 seconds
3 starting for 10 seconds
2 done
4 starting for 2 seconds
5 starting for 10 seconds
4 done
6 starting for 10 seconds
3 done
5 done
6 done
End Demonstration

推荐阅读