为什么shell命令没有按我期望的顺序执行?
问题描述:
我写了3个名为s1.sh s2.sh s3.sh的shell脚本.它们具有相同的内容:
I have written 3 shell scripts named s1.sh s2.sh s3.sh. They have the same content:
#!/bin/ksh
echo $0 $$
和s.sh按顺序调用它们:
and s.sh invoke them in order:
#!/bin/sh
echo $0 $$
exec ./s1.sh &
exec ./s2.sh &
exec ./s3.sh &
但结果是混乱:
victor@ThinkPad-Edge:~$ ./s.sh
./s.sh 3524
victor@ThinkPad-Edge:~$ ./s1.sh 3525
./s3.sh 3527
./s2.sh 3526
为什么s1依次不是s2然后是s3?
why not s1 s2 then s3 in sequence?
如果我删除&在s.sh中:
If I remove & in s.sh:
#!/bin/sh
echo $0 $$
exec ./s1.sh
exec ./s2.sh
exec ./s3.sh
输出:
$ ./s.sh
./s.sh 4022
./s1.sh 4022
为什么缺少s2和s3?
Missing s2 and s3, why?
答
它们已经按顺序执行(至少按顺序开始-请注意,id正在递增).您为3个单独的程序打开3个单独的线程.一个(出于某种原因)比另一个更快.如果要按顺序排列它们,请从exec ./s1.sh &
中取出exec
s和&
s.
They have been executing in order (at least starting in order - Notice the ids are incrementing). You open 3 separate threads for 3 separate programs. One (for some reason) is faster than the other. If you want them in sequence, take the exec
s and &
s out of exec ./s1.sh &
.