bash - 当另一个以 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 次仍然有效)
解决方案
您可以附加&
到命令以在后台运行它,并使用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
推荐阅读
- javascript - HREF有什么办法可以弹出这个吗?
- asp.net-core - 如何解决异常:当前线程与Dispatcher没有关联
- elasticsearch - Nginx 使用 ELK Stack + Kafka 记录管道
- docker - 如何在不退出终端的情况下退出一个命令行进程在没有其他方法的情况下运行?
- javascript - 为什么在使用对象名称时使用“this”关键字不起作用
- java - 按子数组的长度对二维数组进行排序
- json - 如何在 Sql server 中正确索引计算的 json 列?
- php - 使用 Laravel Livewire 向 HTML 表格添加行 - 问题
- python - 根据条件组合数据框列中的行
- asp.net-mvc - 尝试调试时重定向页面