当前位置:首页 > linux教程 > 列表

linux中Shell并发编程示例

发布:smiling 来源: PHP粉丝网  添加日期:2015-04-28 16:03:21 浏览: 评论:0 

Shell是系统的用户界面,提供了用户与内核进行交互操作的一种接口,它接收用户输入的命令并把它送入内核去执行了,下文就来介绍linux中Shell并发编程示例,希望能帮助到各位.

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

那么对于Shell而言,又如何实现呢?其实原理很简单,我采用的方法是.

1.将需要执行的任务分批放入后台执行;

2.将后台执行的命令结果汇总到指定的文件中;

3.使用wait命令来等待所有任务执行结束。

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

  1. vim fastping.sh 
  2. #!/bin/bash 
  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. # function print_help 
  9. function print_help(){ 
  10.   echo "Examples:" 
  11.   echo ${0} 172.17.32 
  12.   echo ${0} 192.168.1 unable 
  13.   exit 1 
  14. } 
  15. # check the parameter 
  16. if [ $# -lt 1 ]; then 
  17.   print_help 
  18. fi 
  19. # check the network parameter's format 
  20. count=0 
  21. for i in $(echo $1 |sed 's/\./ /g') 
  22. do 
  23.   count=$((${count}+1)) 
  24. done 
  25. if [ ${count} -ne 3 ]; then 
  26.   print_help 
  27. fi 
  28. # clean the output file 
  29. > ${output} 
  30. function pingable(){ 
  31.   ping -c ${retry} -w ${timeout} -q ${subnet}.${i} &> /dev/null && echo ${i} >> ${output} 
  32. } 
  33. function unpingable(){ 
  34.   ping -c ${retry} -w ${timeout} -q ${subnet}.${i} &> /dev/null || echo ${i} >> ${output} 
  35. } 
  36. # get the check type 
  37. if [ "$2" == "unable" ]; then 
  38.   status="unpingable" 
  39. else 
  40.   status="pingable" 
  41. fi 
  42. # ping as paraller mode and write output into file 
  43. for i in {1..255} 
  44. do  
  45.   ${status} & 
  46. done 
  47. # wait for all ping processes done 
  48. wait 
  49. # print output with better order 
  50. sum=$(wc -l ${output} |awk '{print $1}') 
  51. echo "There are \"${sum}\" \"${status}\" IPs begin with \"${subnet}.\" :" 
  52. cat ${output} | sort -t"." -k1,1n -k2,2n -k3,3n -k4,4n | xargs -n 20 echo " " 
  53. chmod +x fastping.sh 
  54. ./fastping.sh 
  55. Examples: 
  56. ./fastping 172.17.32 
  57. ./fastping 192.168.1 unable 
  58. time ./fastping.sh 192.168.1 
  59. There are "142" "pingable" IPs begin with "192.168.1" : 
  60.   1 10 12 13 14 15 16 18 19 20 21 22 23 24 25 26 27 28 29 30 
  61.   31 32 33 34 35 36 37 38 40 41 42 43 44 45 46 47 48 49 50 51 
  62.   52 53 54 55 56 57 59 60 61 62 63 64 65 66 67 68 69 70 71 72 
  63.   73 74 75 76 77 78 80 81 83 84 85 86 87 88 89 90 91 92 93 94 
  64.   95 96 97 98 99 100 101 102 103 104 105 106 107 108 112 113 114 115 116 117  //phpfensi.com 
  65.   118 119 120 121 122 123 124 125 126 127 128 133 134 135 136 137 138 139 140 141 
  66.   142 143 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 
  67.   170 254 
  68. real    0m3.201s 
  69. user    0m0.135s 
  70. sys     0m0.495s

Tags: linux并发编程 Shell并发

分享到: