shell模擬併發執行

參考:
http://www.51testing.com/html/28/116228-238978.html
http://blog.chinaunix.net/uid-27571599-id-3473078.html 
  
    在bash中,使用後臺任務來實現任務的多進程化。在不加控制的模式下,不管有多少任務,全部都後臺執行。也就是說,在這種情況下,有多少任務就有多少“進程”在同時執行。
 
實例一:正常腳本(腳本功能:查看一個文件中的IP列表循環測試主機連通性)
[root@ha-drbd-nfs-01-120 ~]# cat ip.txt 
192.168.0.24
192.168.0.25
192.168.0.26
192.168.0.27
192.168.0.28
192.168.0.29
192.168.0.40
192.168.0.41
192.168.0.42
192.168.0.43
192.168.0.81
[root@heartbeat-02-122 ~]# cat ping_host.sh
#!/bin/bash
 
array=$(cat ip.txt)
#echo $array
 
for host in ${array[@]}
do
        {
               ping $host -c 10 -w 1 -i 0.01 -q >/dev/null 2>&1
               ret=$?
               if [ $ret -eq 0 ];then
                        echo "$host isok"
               else
                        echo "$host isbad"
               fi
        }
done
[root@heartbeat-02-122 ~]# time sh ping_host.sh
192.168.0.24 is bad
192.168.0.25 is bad
……………………..
117.79.235.238 is ok
210.14.130.130 is ok
210.14.156.210 is ok
 
real    0m30.688s
user   0m0.099s
sys    0m0.501s
 
實例二:”多進程”實現(無法精確控制併發數量)
[root@heartbeat-02-122 ~]# cat ping_host.sh
#!/bin/bash
 
array=$(cat ip.txt)
#echo $array
 
for host in ${array[@]}
do
        {
                ping $host -c 10 -w 1 -i0.01 -q >/dev/null 2>&1
                ret=$?
                if [ $ret -eq 0];then
                        echo"$host is ok"
                else
                        echo"$host is bad"
                fi
        }&
done
[root@heartbeat-02-122 ~]# time sh ping_host.sh
 
real   0m0.092s
user   0m0.006s
sys    0m0.014s
 
注:就在上面基礎上多加了一個後臺執行&符號,此時應該是所有循環任務併發執行
問題:進程數目不可控制的情況
 
實例三:多線程實現
本實例說明了一種用wait、read命令模擬多線程的一種技巧,此技巧往往用於多主機檢查,比如ssh登錄、ping等等這種單進程比較慢而不耗費cpu的情況,還說明了多線程的控制。
[root@heartbeat-02-122 ~]# cat ping_host.sh
#!/bin/bash
 
tmp_fifofile="/tmp/$.fifo"
mkfifo $tmp_fifofile                 
exec 6<>$tmp_fifofile                
rm $tmp_fifofile
 
thread=5                          
for ((i=0;i<$thread;i++));do
echo
done >&6                         
 
array=$(cat ip.txt)
#echo $array
 
for host in ${array[@]}
do                               
read -u6                           
{                                                   
    ping$host -c 10 -w 1 -i 0.01 -q >/dev/null 2>&1
    ret=$?
    if [$ret -eq 0 ];then
           echo "$host is ok"
    else
           echo "$host is bad"
    fi
       echo >&6                                    
} &
done
 
wait                                                 
exec 6>&-                                           
exit 0
[root@heartbeat-02-122 ~]# time sh ping_host.sh
192.168.0.27 is bad
192.168.0.26 is bad
192.168.0.25 is bad
…………………………….
210.14.156.210 is ok
210.14.130.130 is ok
117.79.235.238 is ok
 
real    0m6.247s
user   0m0.056s
sys    0m0.349s


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章