[plt-scheme] equivalent to atexit?

From: Eli Barzilay (eli at barzilay.org)
Date: Tue Mar 24 01:42:08 EDT 2009

At the Scheme level `exit' will just exit the process, so dynamic wind
etc do nothing.  For example,

  (dynamic-wind void exit (lambda () (printf "bye\n")))

will not do the printout before leaving.

There is a `scheme_add_atexit_closer' function in the mzscheme api,
which might do what you want, for example:

  (require scheme/foreign)
  (unsafe!)
  ((get-ffi-obj "scheme_add_atexit_closer" #f
                (_fun (_fun _scheme _pointer _pointer -> _void)
                      -> _void))
   (lambda (x _1 _2) (printf "bye\n")))

but this is called for managed objects, so you might need to use some
more of the C api to register your objects.  (Or just do whatever you
need, and make sure that there's at least one managed object that will
cause your handler to be called.)

If you prefer a Scheme solution, then perhaps it is better to change
the exit handler:

  (exit-handler (let ([old (exit-handler)])
                  (lambda (s) (printf "bye\n") (old s))))

this will work if you do it when starting your code *and* if you
always exit your program using `exit' (for example, you register an
exception handler to print the error and call `exit' instead of
letting it abort).  But if that's what you're doing, you can just as
well write your own `exit' function that will do the cleanup and then
actually exit.

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.