linux shell创建进程数,[原创]bash shell的并发实现及进程数的控制
首先,要實現(xiàn)并發(fā), 同時運行的進程必須是沒有先后順序的,否則也不適用.比如對多臺server進行ping.
一. 通過后臺運行的方式
常規(guī)方式:
[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
以上兩種運行方式在效率上的差距是很明顯的. 另外上述的這種"并發(fā)"的進程數(shù)是不可控的,即你的循環(huán)上限是多少,并發(fā)的進程數(shù)也會無限接近這個值.
二. 通過管道實現(xiàn)進程數(shù)可控
[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,這里循環(huán)就是向這個描述符里插入了5個占位符
#
for ip in ${iplist[*]}
do
read -u 3;????? ? # 描述符是按行插入和讀取的,每次讀取一次將少一個占位符,直到全部都讀取完后則會等待,等待之前的線程任務完成才可以繼續(xù)新的任務,這樣就達到了控制任務數(shù)的目的。
( 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
這與上面的時間是一樣的,我們調(diào)整進程數(shù)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運行有問題;
閱讀(518) | 評論(0) | 轉(zhuǎn)發(fā)(0) |
總結
以上是生活随笔為你收集整理的linux shell创建进程数,[原创]bash shell的并发实现及进程数的控制的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ()shi linux字符设备,Linu
- 下一篇: Linux改变输出字体颜色,linux下
