【发布时间】:2020-03-30 16:43:32
【问题描述】:
我正在尝试创建一个脚本,该脚本在后台启动一堆作业,然后等待它们全部运行完成。
#!/bin/sh
cleanup() {
wait
echo cleanup
}
do_work() {
sleep 2
echo done "$@"
}
run() {
trap cleanup EXIT
do_work 1 &
# ... some code that may fail ...
do_work 2 &
# I can't just call cleanup() here because of possible early exit
}
# The script itself runs in the background too.
run&
为确保此脚本将等待其所有子进程,即使在生成它们时出现问题,我在最后使用trap cleanup EXIT 而不是仅cleanup。
但是当我在不同的 shell 中运行这个脚本时,我得到了以下结果:
$ for sh in zsh dash 'busybox ash' bash; do echo "$sh:"; $sh script.sh; sleep 3; echo; done
zsh:
done 1
done 2
cleanup
dash:
done 1
done 2
cleanup
busybox ash:
done 2
done 1
cleanup
bash:
done 2
done 1
$
在 Bash 中,陷阱命令似乎被完全忽略了。这可能是什么原因?有什么办法解决吗?
man bash-builtins 说了一些关于在进入 shell 时忽略的信号不能被捕获,但我不知道这如何适用于这种情况......
【问题讨论】: