北京SEO

linux中Shell并发编程示例

2019/10/10/17:45:25  阅读:1781  来源:谷歌SEO算法  标签: Google

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

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

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

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

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

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

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

  1. vimfastping.sh
  2. #!/bin/bash
  3. #defaultsettings
  4. subnet=$1#Ctypesubnet
  5. retry=2#retrytimes
  6. timeout=3#timeoutseconds
  7. output=/tmp/ping.output#outputfile
  8. #functionprint_help
  9. functionprint_help(){
  10. echo"Examples:"
  11. echo${0}172.17.32
  12. echo${0}192.168.1unable
  13. exit1
  14. }
  15. #checktheparameter
  16. if[$#-lt1];then
  17. print_help
  18. fi
  19. #checkthenetworkparameter'sformat
  20. count=0
  21. foriin$(echo$1|sed's/\.//g')
  22. do
  23. count=$((${count}+1))
  24. done
  25. if[${count}-ne3];then
  26. print_help
  27. fi
  28. #cleantheoutputfile
  29. >${output}
  30. functionpingable(){
  31. ping-c${retry}-w${timeout}-q${subnet}.${i}&>/dev/null&&echo${i}>>${output}
  32. }
  33. functionunpingable(){
  34. ping-c${retry}-w${timeout}-q${subnet}.${i}&>/dev/null||echo${i}>>${output}
  35. }
  36. #getthechecktype
  37. if["$2"=="unable"];then
  38. status="unpingable"
  39. else
  40. status="pingable"
  41. fi
  42. #pingasparallermodeandwriteoutputintofile
  43. foriin{1..255}
  44. do
  45. ${status}&
  46. done
  47. #waitforallpingprocessesdone
  48. wait
  49. #printoutputwithbetterorder
  50. sum=$(wc-l${output}|awk'{print$1}')
  51. echo"Thereare\"${sum}\"\"${status}\"IPsbeginwith\"${subnet}.\":"
  52. cat${output}|sort-t"."-k1,1n-k2,2n-k3,3n-k4,4n|xargs-n20echo""
  53. chmod+xfastping.sh
  54. ./fastping.sh
  55. Examples:
  56. ./fastping172.17.32
  57. ./fastping192.168.1unable
  58. time./fastping.sh192.168.1
  59. Thereare"142""pingable"IPsbeginwith"192.168.1":
  60. 110121314151618192021222324252627282930
  61. 3132333435363738404142434445464748495051
  62. 5253545556575960616263646566676869707172
  63. 7374757677788081838485868788899091929394
  64. 9596979899100101102103104105106107108112113114115116117//phpfensi.com
  65. 118119120121122123124125126127128133134135136137138139140141
  66. 142143149150151152153154155156157158159160161162163164165166
  67. 170254
  68. real0m3.201s
  69. user0m0.135s
  70. sys0m0.495s

广告内容

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

相关阅读

热门评论

sunshine技术博客 sunshine技术博客

sunshine技术博客

总篇数164

精选文章

RMAN中catalog和nocatalog区别介绍 小技巧:为Linux下的文件分配多个权限 zimbra8.5.1安装第三方签名ssl证书的步骤 解决mysql不能远程连接数据库方法 windows服务器mysql增量备份批处理数据库 mysql中slow query log慢日志查询分析 JavaScript跨域问题总结 Linux下负载均衡软件LVS配置(VS/DR)教程 mysql中权限参数说明 MYSQL(错误1053)无法正常启动

SEO最新算法