Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: using trap function to cleanup and exit?



On Sun, Apr 10, 2022 at 9:30 AM Greg Klanderman <gak@xxxxxxxxxxxxxx> wrote:
>
> I've tried both exit and return in a list trap, and am not seeing the
> script exit.

The rules for traps and child processes are a bit hard to follow.  If
a signal trap is set to something other than the default in the
parent, then that signal is supposed to be blocked in the child, which
means the signal won't be propagated from the parent to the child.

The following options also control signaling behavior:
MONITOR - off by default in scripts, and when off, causes background
jobs to be left running when the shell exits.
POSIX_JOBS - off by default in native mode, when on forces MONITOR off
in subshells
HUP - on by default, and if MONITOR is also set, causes child
processes to be sent a SIGHUP when the parent exits
TRAPS_ASYNC - off by default, when on the parent handles signals
immediately, otherwise foreground children must exit first
POSIX_TRAPS - off in native mode, modifies the behavior of the EXIT
trap (on in sh/bash/ksh emulations)
LOCAL_TRAPS - off in native mode, saves trap state on function entry
and restores on function return

> Also, is exit intentionally disabled from within a trap function?

No; there was a bugfix for a related thing in 5.6.1 and a couple of
other exit-from-a-trap tweaks involving loop structures that are
pending the next release, but exit from a trap should work (and does
in some simple tests I did).  Do you have a simple example, and are
you sure you're not seeing the effects of some of the above options?

> I didn't expect that, even with the special return handling.  So,
> there is no way to exit 0 from a trap, since that is interpreted as
> the signal having been handled, and wanting to continue executing?

Again I'm not seeing this.  If I exit zero from an INT trap, the exit
status of the interrupted script is zero.  However, if I exit from an
exit trap, the status of the exit trap is ignored and I get the status
from before it was called, e.g., killing a script with SIGINT always
returns 130 even when TRAPEXIT calls exit with a different value.  I'm
not sure that's clearly documented anywhere.

> With no traps of either type, should the child sleep remain after the
> script is killed by a signal?

See above RE signal options.  Probably yes.




Messages sorted by: Reverse Date, Date, Thread, Author