1. 程式人生 > >shell for 迴圈中實現非同步處理

shell for 迴圈中實現非同步處理

理解非同步,需要理解shell殼的原理,父shell和子shell程序之間關係。

shell什麼情況下會產生子程序
下英文摘自info bash
1、後臺執行命令 &。If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell.
2、管道命令 |。Each command in a pipeline is executed in its own subshell。
3、括號命令()。
Placing a list of commands between parentheses causes a subshell
environment to be created
4、執行外部指令碼、程式:
When Bash finds such a file while searching the `$PATH’ for a command, it spawns a subshell to execute it. In other words, executing filename ARGUMENTS is equivalent to executing bash filename ARGUMENTS

核心命令:
等待命令

wait

後臺執行命令

&

程式碼塊,fork子程序

(
)

例項程式碼:
在for迴圈中,非同步執行 單元 ()&:

for i in {1..5}
do
   echo ${i}
   (
     echo block one sleep:${i}
     echo block one_start:`date`
     sleep ${i}          
     echo block one_end:`date`
   )&
     echo Main_One:$!
   ( 
     echo
block tow sleep:1 echo block tow_start:`date` sleep 1 echo block tow:`date` )& echo Main_Tow:$! done echo out:$!

以上測試結果顯示,迴圈中(…)&程式碼,後臺執行後,就fork了一個子進行。

1
Main_One:17976
block one sleep:1  #這裡塊一開始
Main_Tow:17977
2
Main_One:17978
Main_Tow:17980
3
block one sleep:2
Main_One
:17981 Main_Tow:17983 4 Main_One:17984 Main_Tow:17985 5 Main_One:17986 Main_Tow:17987 out:17987 #這裡整個指令碼跑完 block one_start:Wed Jul 18 14:00:29 CST 2018 block one sleep:3 block tow sleep:1 #這裡block二開始執行 block tow sleep:1 block tow sleep:1 block tow sleep:1 block tow sleep:1 block one_start:Wed Jul 18 14:00:29 CST 2018 block one sleep:4 block one sleep:5 block tow_start:Wed Jul 18 14:00:29 CST 2018 block tow_start:Wed Jul 18 14:00:29 CST 2018 block tow_start:Wed Jul 18 14:00:29 CST 2018 block tow_start:Wed Jul 18 14:00:29 CST 2018 block one_start:Wed Jul 18 14:00:29 CST 2018 block tow_start:Wed Jul 18 14:00:29 CST 2018 block one_start:Wed Jul 18 14:00:29 CST 2018 block one_start:Wed Jul 18 14:00:29 CST 2018 block one_end:Wed Jul 18 14:00:30 CST 2018 block tow:Wed Jul 18 14:00:30 CST 2018 block tow:Wed Jul 18 14:00:30 CST 2018 block tow:Wed Jul 18 14:00:30 CST 2018 block tow:Wed Jul 18 14:00:30 CST 2018 block tow:Wed Jul 18 14:00:30 CST 2018 #block二 先結束 block one_end:Wed Jul 18 14:00:31 CST 2018 block one_end:Wed Jul 18 14:00:32 CST 2018 block one_end:Wed Jul 18 14:00:33 CST 2018 block one_end:Wed Jul 18 14:00:34 CST 2018 #block一結束

看到網上有人說for迴圈中,是使用的子程序進行操作,這個結論應該是不合實際的。
只有在顯性的fork了子程序,才有這種現象。在沒有fork子程序的時候,for迴圈是順序執行,等待上一個迴圈結束才會繼續執行。