如果收到SIGINT或SIGTERM,是否需要执行陷阱EXIT? [英] Is trap EXIT required to execute in case of SIGINT or SIGTERM received?

查看:115
本文介绍了如果收到SIGINT或SIGTERM,是否需要执行陷阱EXIT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本

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

,它在不同的shell中的行为不同:

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.

推荐答案

EXIT陷阱无法正常工作方式进入每个外壳。一些示例:

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


  • 在破折号和zsh中,它仅由脚本中的常规退出触发。

  • 在zsh中,如果捕获通常会退出执行的信号,则需要
    通过显式调用 exit 来恢复默认行为。

  • 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.

我建议您实际捕获信号然后退出,它应该在大多数shell中都可移植

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

这篇关于如果收到SIGINT或SIGTERM,是否需要执行陷阱EXIT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆