Bash可以使用 wait
来等待它直接启动的进程 . 但是,如果进程分叉一个子进程,然后执行 bash
(即父进入 bash
),则新执行的Bash进程不能等待"inherited"子进程 . 这是最小的再现:
#/bin/bash
sleep inf &
pid=$!
exec bash -c "wait $pid;"'echo This shell is $$; sleep inf'
这给出了这个输出:
$ bash test.sh
bash: wait: pid 53984 is not a child of this shell
This shell is 53983
然而,pstree表明子pid确实是shell的子代:
$ pstree -p 53983
bash(53983)─┬─sleep(53984)
└─sleep(53985)
似乎Bash在内部跟踪生成的进程,并查询此列表而不是直接调用 waitpid(2)
( zsh
具有相同的问题,但 ksh
按预期工作) . 有没有办法解决这个问题,并让Bash将"inherited"子项添加到其内部结构中?