linux - Bash(并行等待执行)

标签 linux bash

我有一个主脚本,它从一个文件中读取 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 也不错。

关于linux - Bash(并行等待执行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543578/

相关文章:

c++ - 如何在cmake中链接共享对象?

c++ - 如何使用导出函数交叉编译 DLL

python - 当文件夹名称中有空格时使用 `os.path.exists` ?

linux - 在不退出 linux 程序的情况下重新获得 shell 焦点

linux - 如何将字符串拆分为单个字符

linux - Bash 脚本 : Recognizing paths drag-and-dropped to konsole

c - fgets 返回更少的字符

bash - 在 Bash 中重定向 stderr 和 stdout

java - 如何从 bash 向 java 程序发送命令?

linux - 如何理解哈希wget?