linux中Shell并发编程示例
2019/10/10/17:45:25 阅读:1900 来源:谷歌SEO算法 标签:
Google
Shell是系统的用户界面,提供了用户与内核进行交互操作的一种接口,它接收用户输入的命令并把它送入内核去执行了,下文就来介绍linux中Shell并发编程示例,希望能帮助到各位.
在Python中,有很多模块都可以实现并发编程,比如 threading,processing,eventlet 与 Stackless Python 等.
那么对于Shell而言,又如何实现呢?其实原理很简单,我采用的方法是.
1.将需要执行的任务分批放入后台执行;
2.将后台执行的命令结果汇总到指定的文件中;
3.使用wait命令来等待所有任务执行结束。
下面的脚本就用到了这样的并发编程方法,实现的功能是,快速(3-4秒内)对相同C网内的所有IP(255个)通过命令ping进行测试并返回结果,代码如下:
- vimfastping.sh
- #!/bin/bash
- #defaultsettings
- subnet=$1#Ctypesubnet
- retry=2#retrytimes
- timeout=3#timeoutseconds
- output=/tmp/ping.output#outputfile
- #functionprint_help
- functionprint_help(){
- echo"Examples:"
- echo${0}172.17.32
- echo${0}192.168.1unable
- exit1
- }
- #checktheparameter
- if[$#-lt1];then
- print_help
- fi
- #checkthenetworkparameter'sformat
- count=0
- foriin$(echo$1|sed's/\.//g')
- do
- count=$((${count}+1))
- done
- if[${count}-ne3];then
- print_help
- fi
- #cleantheoutputfile
- >${output}
- functionpingable(){
- ping-c${retry}-w${timeout}-q${subnet}.${i}&>/dev/null&&echo${i}>>${output}
- }
- functionunpingable(){
- ping-c${retry}-w${timeout}-q${subnet}.${i}&>/dev/null||echo${i}>>${output}
- }
- #getthechecktype
- if["$2"=="unable"];then
- status="unpingable"
- else
- status="pingable"
- fi
- #pingasparallermodeandwriteoutputintofile
- foriin{1..255}
- do
- ${status}&
- done
- #waitforallpingprocessesdone
- wait
- #printoutputwithbetterorder
- sum=$(wc-l${output}|awk'{print$1}')
- echo"Thereare\"${sum}\"\"${status}\"IPsbeginwith\"${subnet}.\":"
- cat${output}|sort-t"."-k1,1n-k2,2n-k3,3n-k4,4n|xargs-n20echo""
- chmod+xfastping.sh
- ./fastping.sh
- Examples:
- ./fastping172.17.32
- ./fastping192.168.1unable
- time./fastping.sh192.168.1
- Thereare"142""pingable"IPsbeginwith"192.168.1":
- 110121314151618192021222324252627282930
- 3132333435363738404142434445464748495051
- 5253545556575960616263646566676869707172
- 7374757677788081838485868788899091929394
- 9596979899100101102103104105106107108112113114115116117//phpfensi.com
- 118119120121122123124125126127128133134135136137138139140141
- 142143149150151152153154155156157158159160161162163164165166
- 170254
- real0m3.201s
- user0m0.135s
- sys0m0.495s
热门评论