shell脚本并行模板
QQ群:397745473
shell脚本并行模板
1 2 3 4 5
| 参考: https://www.huaweicloud.com/zhishi/arc-3376272.html https://ld246.com/article/1519530562281 http://ask.apelearn.com/m/question/17659 https://www.cnblogs.com/maxgongzuo/p/6414376.html
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #!/bin/bash ip=`cat iplist.txt|grep -v "#"|awk '{print $1}'` dir='/usr/local/src' answer="yes" passwd="123456"
thead_num=50 tmp_fifo_file="/tmp/$$.fifo" mkfifo $tmp_fifo_file exec 4<>$tmp_fifo_file rm -f $tmp_fifo_file
for ((i=0;i<$thead_num;i++))>&4 for i in $ip do read -u4 { expect <&4 }& done wait exec 4>&- exit 0
|
示例:使用 3 个并发,打印出 0-9 10 个数字,并且打印完之后会 sleep 1 秒.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #!/bin/sh
THREAD=3
TMPFILE=$$.fifo
mkfifo ${TMPFILE} exec 7<>${TMPFILE} rm -f ${TMPFILE}
for (( i = 0; i < ${THREAD}; i++ )) do echo >&7 done
function fun(){ echo $i sleep 1 }
for(( i = 0; i < 10; i++ )) do read -u7 { fun echo >&7 } & done
wait
exec 7>&-
echo "finished"
|
很有实战意义:
特点:
$(mktemp) # 建立一个随机的不重名的临时文件
for ((idx=0;idx<$PROCESS_NUM;idx++));
do
echo
done >&6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #!/bin/bash
first_taskid=1 PROCESS_NUM=3
function do_process { local taskid=$2 [ $taskid -eq 1 ] && local gpuid=0 [ $taskid -eq 2 ] && local gpuid=1 [ $taskid -eq 3 ] && local gpuid=3 sh tran.sh $1 $taskid $gpuid & hang $1 $taskid $gpuid }
function hang { while true do sleep 1800 ps -ef|grep "sh tran.sh $1 $2 $3" |grep -v grep [ $? -eq 0 ] && continue || break done echo >&6 }
FIFO_FILE=$(mktemp) rm $FIFO_FILE mkfifo $FIFO_FILE trap "rm $FIFO_FILE" 15 trap "rm $FIFO_FILE" 9 exec 6<>$FIFO_FILE
for ((idx=0;idx<$PROCESS_NUM;idx++)); do echo done >&6
for i in `cat tmp.txt` do read -u6 taskid=$(( $first_taskid % $PROCESS_NUM )) [ $taskid -eq 0 ] && taskid=$PROCESS_NUM do_process $i $taskid & ((first_taskid++)) done
exec 6>&- rm $FIFO_FILE
|
QQ群:397745473