如何等待任何单个子进程终止,在没有等待-n的bash上?

时间:2018-02-02 20:42:06

标签: bash wait child-process

我基本上需要找出wait -n的替代品,我可以在bash的旧版本中使用(例如,bash 4.2,包括在CentOS 7中)等待终止任何子进程(不是所有)。我运气不好吗?陷阱SIGCHLD在我的方案中不起作用。

2 个答案:

答案 0 :(得分:1)

一种方法是使用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

答案 1 :(得分:0)

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

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

这与等待信号并不完全相同,但在功能上它会做同样的事情。