Before answering Joe's question, I would like to remind the readers that keyboard commands and mouse clicks are not the only reason TC shuts down. Windows itself too, sometimes decides to shutdown or restart. Network admin actions, e.g, or simply inactivity, are events that once detected give TC precious little time to finish up either TCExit or anything else it started!
BTW, these last remarks are also relevant to ON CLOSE, -SUSPEND and -SHUTDOWN.
So, in answer to Joe's questions: if you must regularly update persisted state, you can
do that in TCExit, but:
1) it should be short and fast - always.
2) write once for all closing consoles, not every single closing console
ad 1) If your example is the only
thing you would like to do in TCExit, at first glance is seems simple enough that it might reliably work. At second glance I realized a pitfall that makes this statement not universally true (Come to think of it, what is?) Disk drives, whether builtin or as mapped network drives, are often spun down to save energy; your code is no problem if the're all buzzing - but no go if one of them sleeps. It's a great example that nicely demonstrates the vulnerability of the TCExit process.
BTW, restoring (=changing) the current directory in TCStart is not considered good practice. It will effectively defeat any attempt to set the current directory to something useful with start
ad 2) Can be approximated by simply adding the following line to your TCExit
:: Here code that executes for all consoles closing.
:: This tests for the remaining number of shells spawned by our primary shell.
if %_shells gt 0 quit
:: The test above is fast and should thin out the possibilities.
:: Here, put code that should executed by primary shells only.
:: Note that still there can be more than one running in parallel.
:: To find that last console,...
tasklist tcc* > clip:
if %@lines[clip:] ne 0 quit
:: Here we're the last of the Mohicans.
But why not move the work to TCStart instead of TCExit? You can find the state you want in the dir-history which is already maintained and written for you. (set option SaveOnEntry) At startup, search the dir-history backwards until you have found what the last current directory was for each drive you want to restore. No need to redundantly write anything.
[Edit] There is a practical problem with my proposed solution. It is not full proof, but still a huge improvement. The problem is out of scope of this thread.