Tcl/Tk Idiom: At-Exit Callback
Problem
How can a Tcl script schedule a callback to be invoked when the process exits?
Context
It is often useful to be called back when the process exits so that final clean-up operations can be performed. Tcl has no equivalent of the atexit() function from the C standard library.
Forces
- Scripts need to be called back when the process exits.
- The callback mechanism must not require changes to the Tcl interpreter or core C libraries.
- Script libraries do not have control over when the process
exits and so cannot ensure that cleanup operations get called
before a call to
exit,
Solution
Write a Command Interceptor
for the exit command that performs any final operations
as a preprocessing step.
Consequences
The script is called back when the process exits.
This will work even if multiple libraries register At-Exit Callbacks,
as long as all they all rename exit to unique names. Namespaces
should make this unlikey. The At-exit Callbacks will be invoked
in reverse order of registration.
It is difficult to remove At-exit Callbacks during execution if multiple libraries use this idiom.
Known Uses
This idiom was described on the comp.lang.tcl newsgroup by Will Colleda and suggested as a pattern by Cameron Laird.