Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2448597
  • 博文数量: 540
  • 博客积分: 11289
  • 博客等级: 上将
  • 技术积分: 6160
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-11 20:27
个人简介

潜龙勿用,见龙在田

文章分类

全部博文(540)

文章存档

2018年(2)

2013年(5)

2012年(24)

2011年(104)

2010年(60)

2009年(217)

2008年(128)

分类: LINUX

2010-12-02 17:17:22

首先,要实现并发, 同时运行的进程必须是没有先后顺序的,否则也不适用.比如对多台server进行ping.

一. 通过后台运行的方式
常规方式:
[root@vm57-120 ~]# cat ping.sh
#!/bin/bash
for ip in 192.168.57.121 192.168.57.122 192.168.57.123
do
{ ping -c 20 $ip >/tmp/$ip.log; }
done
wait
wc -l /tmp/*.log
# time sh ping.sh
  25 /tmp/192.168.57.121.log
  25 /tmp/192.168.57.122.log
  25 /tmp/192.168.57.123.log
  75 total

real    0m57.073s
user    0m0.012s
sys     0m0.014s
后台运行方式:
[root@vm57-120 ~]# cat mping.sh
#!/bin/bash
for ip in 192.168.57.121 192.168.57.122 192.168.57.123
do
{ ping -c 20 $ip >/tmp/$ip.log; } &
done
wait
wc -l /tmp/*.log
[root@vm57-120 ~]# time sh mping.sh
  25 /tmp/192.168.57.121.log
  25 /tmp/192.168.57.122.log
  25 /tmp/192.168.57.123.log
  75 total

real    0m19.037s
user    0m0.014s
sys     0m0.023s

以上两种运行方式在效率上的差距是很明显的. 另外上述的这种"并发"的进程数是不可控的,即你的循环上限是多少,并发的进程数也会无限接近这个值.

二. 通过管道实现进程数可控
[root@vm57-120 ~]# vim eping.sh

#!/bin/bash
pipefile=$$.fifo
mkfifo $pipefile
exec 3<>$pipefile
rm $pipefile
iplist=(192.168.57.121 192.168.57.122 192.168.57.123)
thread=5;
for (( i = 1;i<=${thread};i++ ))
do
echo;
done >&3;        # &3代表引用文件描述符3,这里循环就是向这个描述符里插入了5个占位符

#
for ip in ${iplist[*]}
do
read -u 3;        # 描述符是按行插入和读取的,每次读取一次将少一个占位符,直到全部都读取完后则会等待,等待之前的线程任务完成才可以继续新的任务,这样就达到了控制任务数的目的。
( ping -c 20 $ip >/tmp/$ip.log;echo >&3 ) &
done
wait
exec 3>&-;            #关闭定义的管道
wc -l /tmp/*.log
[root@vm57-120 ~]# time sh eping.sh
  25 /tmp/192.168.57.121.log
  25 /tmp/192.168.57.122.log
  25 /tmp/192.168.57.123.log
  75 total

real    0m19.037s
user    0m0.014s
sys     0m0.030s
这与上面的时间是一样的,我们调整进程数thread=2:
[root@vm57-120 ~]# time sh eping.sh
  25 /tmp/192.168.57.121.log
  25 /tmp/192.168.57.122.log
  25 /tmp/192.168.57.123.log
  75 total

real    0m38.042s
user    0m0.012s
sys     0m0.032s


{ } &大括号丢到后台时,最后需要一个分号;  { cmd1;cmd2;} &
( cmd ) & 小括号必须放到脚本里运行才可以;在当前shell运行有问题;
阅读(1379) | 评论(0) | 转发(0) |
0

上一篇:nginx status

下一篇:fifo(7) - Linux man page

给主人留下些什么吧!~~