如何在 bash 上等待任何单个子进程终止而无需等待 -n?

How to wait for any single child process to terminate, on a bash without wait -n?

我基本上需要想出一个 wait -n 的替代品,我可以在旧版本的 bash 中使用(例如,CentOS 7 中包含的 bash 4.2)以等待终止 any 子进程(不是 all)。我运气不好吗?诱捕 SIGCHLD 在我的场景中不起作用。

如果您知道 PID,最明显的解决方案是:

while ps $pid > /dev/null ; do
    sleep 1
done

这与等待信号不太一样,但在功能上它会做同样的事情。

一种方法是使用 FIFO 在退出时发送通知:

mkfifo notify_fd
exec 3<>notify_fd
count=0

background() { { "$@"; echo "${BASHPID} $?" >&3; } & (( ++count )); }

background sleep 3
background sleep 4
background sleep 5

while read pid status <&3; do
  echo "One exited, with PID $pid and status $status"
  (( --count == 0 )) && break
done