Is it necessary to specify traps other than EXIT?

最后都变了- 提交于 2019-12-02 20:12:06
Brandon Horsley

I think trap 0 is executed just prior to script termination in all cases, so is useful for cleanup functionality (like removing temporary files, etc). The other signals can have specialized error handling but should terminate the script (that is, call exit).

What you have described, I believe, would actually execute cmd twice. Once for the signal (for example SIGTERM) and once more on exit (trap 0).

I believe the proper way to do this is like the following (see POSIX specification for trap):

trap "rm tmpfile" 0
trap "exit 1" TERM HUP ... 

This ensures a temporary file is removed upon script completion, and lets you set custom exit statuses on signals.

NOTE: trap 0 is called whether a signal is encountered or not.

If you are not concerned with setting an exit status, trap 0 would be sufficient.

To make sure the EXIT signal handler will not be executed twice (which is almost always not what you want) it should always set to be ignored or reset within the definition of the EXIT signal handler itself.

The same goes for signals that have more than one signal handler defined for them in a program.

# reset
trap 'excode=$?; cmd; trap - EXIT; echo $excode' EXIT HUP INT QUIT PIPE TERM

# ignore
trap 'excode=$?; trap "" EXIT; cmd; echo $excode' EXIT HUP INT QUIT PIPE TERM

The shell standard does not specify whether a trap on 0 is executed when an untrapped signal is received. In particular, bash and dash behave differently. Given trap cmd-list 0 with no traps set for any signals, bash will execute the cmd-list upon receipt of SIGTERM, but dash will not. Given trap cmd-list 0 2, bash executes cmd-list once upon receipt of SIGTERM, and dash executes cmd-list twice.

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