973114 发表于 2018-8-28 13:24:20

shell模拟并发执行

参考:  
http://www.51testing.com/html/28/116228-238978.html
  
http://blog.chinaunix.net/uid-27571599-id-3473078.html
  

  
    在bash中,使用后台任务来实现任务的多进程化。在不加控制的模式下,不管有多少任务,全部都后台执行。也就是说,在这种情况下,有多少任务就有多少“进程”在同时执行。
  

  
实例一:正常脚本(脚本功能:查看一个文件中的IP列表循环测试主机连通性)
  
# 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
  
# 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
  
# 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
  

  
实例二:”多进程”实现(无法精确控制并发数量)
  
# 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
  
# time sh ping_host.sh
  

  
real   0m0.092s
  
user   0m0.006s
  
sys    0m0.014s
  

  
注:就在上面基础上多加了一个后台执行&符号,此时应该是所有循环任务并发执行
  
问题:进程数目不可控制的情况
  

  
实例三:多线程实现
  
本实例说明了一种用wait、read命令模拟多线程的一种技巧,此技巧往往用于多主机检查,比如ssh登录、ping等等这种单进程比较慢而不耗费cpu的情况,还说明了多线程的控制。
  
# 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&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
  
# 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


页: [1]
查看完整版本: shell模拟并发执行