linux shell|linux中Shell并发编程示例

更新时间:2019-07-18    来源:python    手机版     字体:

【www.bbyears.com--python】

在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 "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

本文来源:http://www.bbyears.com/jiaocheng/58622.html

热门标签

更多>>

本类排行