shell 'trap' woodoo :)

Cristian Ionescu-Idbohrn cristian.ionescu-idbohrn at axis.com
Sun Sep 12 07:42:04 UTC 2010


On Sat, 11 Sep 2010, Cristian Ionescu-Idbohrn wrote:

> This test script:
>
> ---8<---
> #!/bin/sh
>
> set -e
> set -u
> #set -x
>
> trap 'wrapper_func' EXIT TERM INT
>
> other_func() {
> 	echo "in : other_func" >&2
> # XXX:	if this doesn't fail, the expected exit status comes out after 'trap'
> #	but, if it _does_ fail, the exit status of the failed command will
> #	be returned, as errexit will step in.
> 	ls -al /foo/bar/baz || :
> 	echo "out: other_func" >&2
> }
>
> wrapper_func() {
> 	echo "in : wrapper_func" >&2
> 	date +%s >/dev/null
> 	echo "1. : wrapper_func: listing traps" >&2
> 	trap
> 	echo "2. : wrapper_func: removing traps" >&2
> 	trap - EXIT INT TERM
> 	echo "3. : wrapper_func: listing traps again" >&2
> 	trap
> 	other_func
> 	echo "out: wrapper_func" >&2
> }
>
> echo "running: $0" >&2
> sleep 5
>
> exit 77
> --->8---
>
> does not behave as expected if the shell is ash, hush or dash.  Bash on
> debian unstable:
>
> 	GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu)
> 	Copyright (C) 2009 Free Software Foundation, Inc.
> 	License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
>
> does TRT, though.
>
> All shells run the trap action twice when hitting C-c with trap on INT.
> With signals removed in the trap action, only bash behaves, according to
> my experiments.

Oh, I missed this: hitting C-c while 'sleep 5' executes will not interrupt
the sleep (ash and hush).  Seems C-c is ignored.  Both SIGINT and SIGTERM
are ignored.

+ trap wrapper_func EXIT TERM INT
+ echo running: /home/cii/axis/tests/trap-test3.sh
running: /home/cii/axis/tests/trap-test3.sh
+ sleep 5
^C^C^C^C^C^C^C^C^C^C^C^C+ wrapper_func
+ echo in : wrapper_func
in : wrapper_func
+ date +%s
+ echo 1. : wrapper_func: listing traps
1. : wrapper_func: listing traps
+ trap
trap -- 'wrapper_func' EXIT
trap -- 'wrapper_func' INT
trap -- 'wrapper_func' TERM
+ echo 2. : wrapper_func: removing traps
2. : wrapper_func: removing traps
+ trap - EXIT INT TERM
+ echo 3. : wrapper_func: listing traps again
3. : wrapper_func: listing traps again
+ trap
+ other_func
+ echo in : other_func
in : other_func
+ ls -al /foo/bar/baz
ls: /foo/bar/baz: No such file or directory
+ :
+ echo out: other_func
out: other_func
+ echo out: wrapper_func
out: wrapper_func
+ exit 77

Dash and dash behave as expected WRT reacting to C-c.


Cheers,

-- 
Cristian


More information about the busybox mailing list