欢迎光临
我们一直在努力

shell并发编程

本站教程收集整理的这篇文章主要介绍了shell并发编程,本站教程本站觉得挺不错的,现在分享给大家,也给大家做个参考。

在Python中,有很多模块都可以实现并发编程,比如 threading,processing,eventlet 与 stackless Python 等。

那么对于SHell而言,又如何实现呢?其实原理很简单,我采用的方法是:
1. 将需要执行的任务分批放入后台执行;
2. 将后台执行的命令结果汇总到指定的文件中;
3. 使用wait命令来等待所有任务执行结束。

下面的脚本就用到了这样的并发编程方法,实现的功能是:
快速(3-4秒内)对相同C网内的所有IP(255个)通过命令ping进行测试并返回结果。

vim fastping.sh

#!/bin/bash 

# default setTings
subnet=$1 # C type subnet
retry=2 # retry times
timeout=3 # timeout seconds
output=/tmp/ping.output # output file

# function print_Help
function print_Help(){
  echo 美国高防vps "Examples:"
  echo ${0} 172.17.32
  echo ${0} 192.168.1 unable
  exit 1
}

# check the parameter
if [ $# -lt 1 ]; then
  print_Help
fi

# check the network parameter's format
count=0
for i in $(echo $1 |sed 's/\./ /g')
do
  count=$((${Count}+1))
done
if [ ${Count} -ne 3 ]; then
  print_Help
fi

# clean the output file
> ${output}

function pingable(){
  ping -c ${retry} -w ${timeout} -q ${subnet}.${i} &> /dev/null && echo ${i} >> ${output}
}

function unpingable(){
  ping -c ${retry} -w ${timeout} -q ${subnet}.${i} &> /dev/null || echo ${i} >> ${output}
}

# get the check type
if [ "$2" == "unable" ]; then
  status="unpingable"
else
  status="pingable"
fi

# ping as paraller mode and write output into file
for i in {1..255}
do 
  ${status} &
done

# wait for all ping processes done
wait

# print output with better order
sum=$(wc -l ${output} |awk '{print $1}')
echo "There are \"${sum}\" \"${status}\" IPs begin with \"${subnet}.\" :"
cat ${output} | sort -t"." -k1,1n -k2,2n -k3,3n -k4,4n | xargs -n 20 echo " "

chmod +x fastping.sh
./fastping.sh

Examples:
./fastping 172.17.32
./fastping 192.168.1 unable

time ./fastping.sh 192.168.1

There are "142" "pingable" IPs begin with "192.168.1" :
  1 10 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 28 29 30
  31 32 33 34 35 36 37 38 40 41 42 43 44 45 46 47 48 49 50 51
  52 53 54 55 56 57 59 60 61 62 63 64 65 66 67 68 69 70 71 72
  73 74 75 76 77 78 80 81 83 84 85 86 87 88 89 90 91 92 93 94
  95 96 97 98 99 100 101 102 103 104 105 106 107 108 112 113 114 115 116 117
  118 119 120 121 122 123 124 125 126 127 128 133 134 135 136 137 138 139 140 141
  142 143 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  170 254

real    0m3.201s
user    0m0.135s
sys     0m0.495s

本站总结

以上是本站教程为你收集整理的shell并发编程全部内容,希望文章能够帮你解决shell并发编程所遇到的程序开发问题。

如果觉得本站教程网站内容还不错,欢迎将本站教程推荐给好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。