为什么后台作业有随机行为?

为什么后台作业有随机行为?

正在经历高级 bash 脚本编写指南示例 3.3 在后台运行循环,我发现:

#!/bin/bash
# background-loop.sh
for i in 1 2 3 4 5 6 7 8 9 10 # First loop.
do
echo -n "$i "
done & # Run this loop in background.
# Will sometimes execute after second loop.
echo # This 'echo' sometimes will not display.
for i in 11 12 13 14 15 16 17 18 19 20 # Second loop.
do
echo -n "$i "
done
echo # This 'echo' sometimes will not display.
# ======================================================
# The expected output from the script:
# 1 2 3 4 5 6 7 8 9 10
# 11 12 13 14 15 16 17 18 19 20
# Sometimes, though, you get:
# 11 12 13 14 15 16 17 18 19 20
# 1 2 3 4 5 6 7 8 9 10 bozo $
# (The second 'echo' doesn't execute. Why?)
# Occasionally also:
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# (The first 'echo' doesn't execute. Why?)
# Very rarely something like:
# 11 12 13 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 19 20
# The foreground loop preempts the background one.
exit 0

# Nasimuddin Ansari suggests adding sleep 1
#+ after the echo -n "$i" in lines 6 and 14,
#+ for some real fun.

我不明白这一点,有人明白这一点吗?

答案1

后台作业异步执行。这意味着您可以仅根据定义来预测执行顺序。理论上,即使添加,sleep您仍然可能会遇到问题:仅等待几秒钟并不能消除 bg 作业的异步性质,您实际做的唯一事情就是降低这种混淆的可能性。

相关内容