I'm looking for a builtin or standard package that provides functionality that is similar or equivalent to stdlib's atexit()
and bash' trap "..." EXIT
.
It should catch termination due to any programatic way of ending execution, including all of the following:
exit
error
In most cases, all you need to do to intercept such terminations is to intercept the exit
command.
rename exit real_exit
proc exit args {
puts "EXITING"; flush stdout; # Flush because I'm paranoid...
tailcall real_exit {*}$args
}
That will obviously work if you call it explicitly, but it also gets called if you just drop off the end of the script, signal end of file in an interactive session, or if your script has an error in it later and terminates with an error message. This is because the Tcl C API call, Tcl_Exit()
, works by calling exit
and, if that doesn't exit the process, directly does the exit itself.
Be careful with exit scripts BTW; errors in them are harder to debug than normal.
The cases where it doesn't work? Mainly where the interpreter itself has become unable to execute commands (perhaps because it has been deleted out from under itself) or where some signal closes down the interpreter (e.g., SIGINT isn't handled by default for various reasons).