Is trap EXIT required to execute in case of SIGINT or SIGTERM received?

不打扰是莪最后的温柔 提交于 2019-12-08 17:36:53

问题


I have a simple script

trap 'echo exit' EXIT
while true; do sleep 1; done

and it behaves differently in different shells:

$ bash tst.sh
^Cexit
$ dash tst.sh
^C
$ zsh tst.sh
^C
$ sh tst.sh
^Cexit

So I'm not sure about how it should operate and whether it is specified at all.


回答1:


The EXIT trap isn't working the same way in every shell. A few examples:

  • In dash and zsh it's only triggered by a regular exit from within the script.
  • In zsh, if you trap a signal that would normally quit the execution, you need to restore the default behaviour by explicitly calling exit.

I'd suggest you to actually catch the signals and then exit, it should be portable across most shells:

$ cat trap
trap 'echo exit; exit' INT TERM  # and other signals
while true; do sleep 1; done
$ bash trap
^Cexit
$ dash trap
^Cexit
$ zsh trap
^Cexit
$ ksh trap
^Cexit
$ mksh trap
^Cexit
$ busybox sh trap
^Cexit


来源:https://stackoverflow.com/questions/27012762/is-trap-exit-required-to-execute-in-case-of-sigint-or-sigterm-received

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!