我有一个主脚本,它从一个文件中读取 5 行并一次执行 5 个不同的 shell 脚本并等待 5 个脚本完成后再开始下一批:
cat file |
while read line1 && read line2 && read line3 && read line4 && read line5
sh script1.sh &
sh script2.sh &
sh script3.sh &
sh script4.sh &
sh script5.sh &
wait
有没有办法确保即使脚本 {1,3} 已完成,也总是有 5 个脚本同时运行。即如果 1-5 同时运行并且 1,2 完成。立即开始 6,7。
有趣的问题!我能想到的最好的方法是保留一个进程的 PID 数组,如果数组中的 PID 少于五个,则创建一个新进程。像这样:
while read line1 && read line2 && read line3 && read line4 && read line5 ; do
sh script1.sh &
PIDS+=($!)
sh script2.sh &
PIDS+=($!)
sh script3.sh &
PIDS+=($!)
sh script4.sh &
PIDS+=($!)
sh script5.sh &
PIDS+=($!)
for PID in "${PIDS[@]}"; do
if ! kill -0 "$PID"; then # If the PID is not alive
if [ ${#PIDS[@]} -lt 5 ]; then
echo "Process $PID dead, starting new one"
sh scriptN.sh &
PIDS+=($!)
fi
fi
done
done
它仍然需要一些工作,但希望这能给您带来灵感。如果可用的话,GNU Parrallel 也不错。