shell併發程式設計

shuilaner_發表於2017-11-18

在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

相關文章