cygwin bash 没有等待后台脚本完成

cygwin bash not waiting for background scripts to finish

我在等待后台作业时遇到问题;我用以下基本结构设置了两个脚本:

主脚本:

cat list_of_names.txt | while read name; do

  ./my_script_1.sh $name &

done

wait

./other_process.exe

my_script_1.sh:

name=

./prog_1.exe $name
./prog_2.exe $name
./prog_3.exe $name

程序 other_process.exe 只能 运行 一旦 myscript.sh 的所有后台实例完成 运行ning。问题是对 wait 的调用不会等待这些后台进程完成,而是主脚本立即 运行s other_process.exe (失败)。

在尝试调试时,我发现在 while 循环中调用 jobs 可以正确显示 myscript.sh 的所有后台实例 运行ning .但是,在 wait 命令 returns 之前在循环外调用 jobs 什么也没有。据我所知,一旦主脚本完成 while 循环,它就再也看不到由它启动的任何子进程。

这不是 cygwin 特有的。 bash 中的管道在 subshell 中开始其命令。因此,后台进程是 subshell 的子进程,而不是 main shell 的子进程。避免使用管道,将其替换为进程替换 <( ... ):

#!/bin/bash
while read x ; do
    ( echo Start $x ; sleep $x ; echo Done $x ) &
done < <( echo $'1\n2' )
echo Done start
wait
echo Done all