2011-03-24 67 views
1

我正在扩展我对bash脚本的知识。我遇到以下代码片段:后台循环问题

!/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 word # This 'echo' sometimes will not display. 

看来这段代码的输出是非确定性的;我想知道为什么...

编辑:迄今;在10次“字”是始终显示

EDIT2: 样本输出:

11 1 12 13 14 2 15 3 16 4 17 5 18 6 19 7 20 8 9 word 
1 11 12 13 2 14 3 15 4 16 5 17 6 18 7 19 8 20 9 10 word 
11 12 13 14 1 15 16 17 2 18 3 19 4 20 5 6 word 
+2

的将会成为一个问题。每一个真正的单词,而不是一个空白的行。你看不到空白的回声,所以你认为什么都没有发生。更改回声后,请**更新**您的问题以包含实际错误实际示例的实际日志。 – 2011-03-24 21:51:59

+2

打开你的调试'set -vx',我打赌你看到所有的命令都被执行了。 – shellter 2011-03-24 21:53:56

+0

@shellter我执行'set -vx'然后运行脚本;除了看到我跑过的脚本的名字以外,我的结果都是非确定性的,除了看到我的脚本名称 – bbaja42 2011-03-24 22:15:57

回答

3

基本上这里发生的一切是你有2个进程同时运行。和往常一样,你无法预测它们将以什么顺序执行。来自第一个for循环的输出和第二个for循环的输出的每个组合都是可能的。

4

在后台运行的循环或任何命令与脚本的其余部分同时运行。如果您有多核机器,它可能在不同的处理器上运行。事情的顺序取决于核心数量,系统的繁忙程度以及操作系统调度程序的意念。

由于大量的I/O从多个进程到同一个终端/文件/任何,你甚至可能会看到输出混在一起。

+0

但为什么会有一个'echo'命令不显示?评论“这个'echo'有时不会显示”来自[高级Bash脚本指南]中的原始代码片段(http://www.tldp.org/LDP/abs/html/special-chars.html#BGLOOP ),但它不能解释为什么:( – 2016-09-21 02:12:25

0

您可以在脚本BG任务等待如下:“回声#这‘回响’有时不会显示”

# create a sentinel for exiting (is this the right term?) 
export sentinel=".stopBgTask.$$" 
# Run in the background and wait for sentinel to be created 
i=1 
while [ ! -e "$sentinel" ] 
do echo $i 
    i=$(($i + 1)) 
    sleep 1 
done & # uncomment the & when you have no script errors 

echo "Parent sleeping for a few seconds" 
sleep 3 
echo "stop the background task" > $sentinel 
echo "Waiting for bg task to end..." 
wait $! # wait for last bg task to end (kill $! would work too) 
rm $sentinel 
echo "We are done!"