任务队列+并行化+动态添加
该脚本使用 FIFO 分叉自身来处理队列。这样,您可以动态地将命令添加到队列中(当队列已经启动时)。
用法:./queue 命令 [# of children] [队列名称]
例如,有 1 个线程:
./queue “睡眠 5;回显一”
./queue “回声二”
输出:
一
二
例如,有 2 个线程:
./queue “睡眠 5;回显一” 2
./queue “回声二”
输出:
二
一
例如,有 2 个队列:
./queue "睡眠 5;回显 ONE queue1" 1 queue1
./queue "睡眠 3;回显 ONE queue2" 1 queue2
输出:
一个队列2
一个队列1
脚本(将其保存为“队列”和 chmod +x 队列):
#!/bin/bash
#Print usage
[[ $# -eq 0 ]] && echo Usage: $0 Command [# of children] [Queue name] && exit
#Param 1 - Command to execute
COMMAND="$1"
#Param 2 - Number of childs in parallel
MAXCHILD=1
[[ $# -gt 1 ]] && MAXCHILD="$2"
#Param 3 - File to be used as FIFO
FIFO="/tmp/defaultqueue"
[[ $# -gt 2 ]] && FIFO="$3"
#Number of seconds to keep the runner active when unused
TIMEOUT=5
runner(){
#Associate file descriptor 3 to the FIFO
exec 3<>"$FIFO"
while read -u 3 -t $TIMEOUT line; do
#max child check
while [ `jobs | grep Running | wc -l` -ge "$MAXCHILD" ]; do
sleep 1
done
#exec in backgroud
(eval "$line")&
done
rm $FIFO
}
writer(){
#fork if the runner is not running
lsof $FIFO >/dev/null || ($0 "QueueRunner" "$MAXCHILD" "$FIFO" &)
#send the command to the runner
echo "$COMMAND" > $FIFO
}
#Create the FIFO file
[[ -e "$FIFO" ]] || mkfifo "$FIFO"
#Start the runner if in the runner fork, else put the command in the queue
[[ "$COMMAND" == "QueueRunner" ]] && runner || writer