Chinaunix首页 | 论坛 | 博客
  • 博客访问: 95349
  • 博文数量: 15
  • 博客积分: 126
  • 博客等级: 入伍新兵
  • 技术积分: 324
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-20 08:46
文章分类
文章存档

2013年(15)

我的朋友

分类: LINUX

2013-04-25 22:56:13

把脚本从顺序执行改成并发执行,提高脚本执行效率

2011-01-04 09:13 来源: nivek.cublog.cn 作者:nivek 网友评论 0 条 浏览次数 33
#!/bin/bash
if [ 1 -eq 1 ];then
echo "this is first step!"|tee -a 8first.txt
sleep 3
else
echo "wrong"
fi

if [ 2 -eq 2 ];then
echo "this is second step!"|tee -a 9sec.txt
else
echo "wrong"
fi

看上面的脚本,从功能块来看,它分两块,对于这两个逻辑上并不存在关系的两个模块,如果我想让它们同时执行而非现在的有先后顺序,一步一步的,浪费时间

简单的做法是这样的,把上面两个功能模块写成两个小的脚本,然后再在脚本里面去调用这两个小的脚本,这里调用并非简单的去执行它,而必须将它们放在

后台执行,即如下:

#!/bin/bash
./1test.sh &
./2test.sh &



这种做法姑且也称增加程序的并发度吧!


情况可能没有这样简单,我需要这些后台脚本跑完后再继续执行脚本里面剩下的内容,于是:

........

. /app/project/sh/kevin1.sh &

. /app/project/sh/kevin2.sh &



wait $!

if [ $? -eq 0 ];then

..........

fi

这里“wait $!” 是关键,意思是说看最后的那个后台进程执行是否结束



对于$!的标准解释:

$! PID of the last process placed in the background. This num-

ber is needed to kill the process.



对于wait命令的标准解释:

wait [PID]

Wait until child process has finished. If no option

is set the script will wait until all child processes

have finished.


这样仍然有问题,因为在后台运行时,各自运行时间长短不一,我们必须得等所有的后台任务都结束了,才可以继续执行脚本后面的内容,则需要如下方式:
#!/bin/bash
. ./1.sh &
i=$!
. ./2.sh &
j=$!
wait $i && wait $j
if [ $? -eq 0 ];then
echo "success!"
....

阅读(1484) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~