shell并发编程

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

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

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

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

vim fastping.sh

  1. #!/bin/bash
  2.  
  3. # default settings
  4. subnet=$1 # C type subnet
  5. retry=2 # retry times
  6. timeout=3 # timeout seconds
  7. output=/tmp/ping.output # output file
  8.  
  9. # function print_help
  10. function print_help(){
  11. echo "Examples:"
  12. echo ${0} 172.17.32
  13. echo ${0} 192.168.1 unable
  14. exit 1
  15. }
  16.  
  17. # check the parameter
  18. if [ $# -lt 1 ]; then
  19. print_help
  20. fi
  21.  
  22. # check the network parameter's format
  23. count=0
  24. for i in $(echo $1 |sed 's/\./ /g')
  25. do
  26. count=$((${count}+1))
  27. done
  28. if [ ${count} -ne 3 ]; then
  29. print_help
  30. fi
  31.  
  32. # clean the output file
  33. > ${output}
  34.  
  35. function pingable(){
  36. ping -c ${retry} -w ${timeout} -q ${subnet}.${i} &> /dev/null && echo ${i} >> ${output}
  37. }
  38.  
  39. function unpingable(){
  40. ping -c ${retry} -w ${timeout} -q ${subnet}.${i} &> /dev/null || echo ${i} >> ${output}
  41. }
  42.  
  43. # get the check type
  44. if [ "$2" == "unable" ]; then
  45. status="unpingable"
  46. else
  47. status="pingable"
  48. fi
  49.  
  50. # ping as paraller mode and write output into file
  51. for i in {1..255}
  52. do
  53. ${status} &
  54. done
  55.  
  56. # wait for all ping processes done
  57. wait
  58.  
  59. # print output with better order
  60. sum=$(wc -l ${output} |awk '{print $1}')
  61. echo "There are \"${sum}\" \"${status}\" IPs begin with \"${subnet}.\" :"
  62. cat ${output} | sort -t"." -k1,1n -k2,2n -k3,3n -k4,4n | xargs -n 20 echo " "

chmod +x fastping.sh
./fastping.sh

  1. Examples:
  2. ./fastping 172.17.32
  3. ./fastping 192.168.1 unable

time ./fastping.sh 192.168.1

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

猜你在找的Bash相关文章