shell编程笔记3–shell并发
介绍
在shell中适当使用并发功能可以提高任务执行的效率,例如:for循环拷贝100台机器上的小文件,若能使用并发则可以提高近100倍效率。为了适当提高shell的并发效率,笔者总结了2种常见的shell并发方式,分别为:简单后台方式,普通控制并发量方式,通过管道控制并发量方式。
并发方法
1. 简单后台方式
- 实现方法
function test_scp(){
echo 'test_scp!'
abspath=$(cd "$(dirname "$0")"; pwd)
filename=$abspath'/'$1/$1'_on.log'
pathname1=$abspath'/'$1'/netstat'
pathname2=$abspath'/'$1'/netstat_all'
pathname3=$abspath'/'$1'/iptables'
if [ ! -d $pathname1 ];then
mkdir $pathname1
fi
if [ ! -d $pathname2 ];then
mkdir $pathname2
fi
if [ ! -d $pathname3 ];then
mkdir $pathname3
fi
iplist=$(cat $filename|tr -d '\r')
for i in $iplist
do
{
scp $i:~/netstat.log $pathname1/$i'_netstat.log'
scp $i:~/netstat-all.log $pathname2/$i'_all_netstat.log'
scp $i:~/file/backup/iptables/iptables.save $pathname3/$i'_iptables.save'
}&
done
}
project='projectName'
test_scp $project
该方法在for的do done之间增加了{}&,该方式将scp分别放到后台处理,对于这类资源消耗少的小作业可以提高x倍效率; 其中 $1_on.log即为可访问的ip,按行存放到xx_on.log中.
- 优点
简单, 比较适用于耗资源少的任务.
- 缺点
当shell命令消耗很多内存时候,容易导致机器挂掉或者异常.
2. 普通控制并发量方式
- 实现方法
可以在循环中套循环,并配合wait实现并发量控制,如下使用5个并发量执行程序,案例如下:
shell脚本:#!/bin/bash
i=1
while ((i<=20))
do
echo 'i='$i
for ((j=1; j<=5; j++))
do
{
python test.py
}&
((i++))
done
wait
done
echo $i
python脚本:#!/usr/bin/python
import os
import time
import random
rm = random.randint(1,10)
time.sleep(rm)
print("pid="+str(os.getpid())+",rand="+str(rm))
输出结果如下:$ bash test_muti.sh
i=1
pid=31171,rand=3
pid=31177,rand=3
pid=31178,rand=8
pid=31176,rand=10
pid=31174,rand=10
i=6
pid=31194,rand=1
pid=31195,rand=2
pid=31191,rand=5
pid=31193,rand=7
pid=31192,rand=8
i=11
pid=31205,rand=3
pid=31200,rand=5
pid=31204,rand=8
pid=31202,rand=9
pid=31203,rand=10
i=16
pid=31215,rand=2
pid=31214,rand=2
pid=31211,rand=7
pid=31216,rand=7
pid=31209,rand=9
21
- 优点
简单,每次需要等wait上面的5个进程执行完。
- 缺点
没有时刻保持4-5个进程同时运行,每次需要5个进程全部执行完了才会进行下一轮并发。
3. 通过管道控制并发量
待补充…
参考文献
1. 如何用shell脚本并行多个命令
2. Linux Shell多进程并发以及并发数控制