Re: [Q] Exit hook for a "C" extension module

Steven D. Majewski (sdm7g@virginia.edu)
Wed, 15 Mar 1995 11:05:48 -0500 (EST)

On Wed, 15 Mar 1995, Ken Manheimer wrote:

> On Wed, 15 Mar 1995, Raymond E. Suorsa wrote:
>
> > [...]
> > Simply put: How do I supply an exit hook for a module (i.e. how do I
> > run clean up code before python exits. This is to unlink shared memory
> > that will still exist even after python shuts down normally.)
>
> Assign your exit function to sys.exitfunc - it will get called when
> python exits. (This works whether you explicitly call sys.exit() to
> exit, or the interpreter encounters an <eof>, or whatever. The exit func
> will not get called, however, if you exit via os._exit().)
>
> >>> def done(): print 'done'
> ...
> >>> sys.exitfunc = done
> >>> sys.exit(0)
> done
> %

Unfortunately, using sys.exitfunc means that another module can
clobber sys.exitfunc and your cleanup will never get done. Maybe
there should be a class wrapped around an exit function list,
with add and remove from list methods.

However, for modules written in C, there already is an
add-exit-function-to-cleanup-list method.

In pythonrun.c:

int Py_AtExit(func)
void (*func) PROTO((void));
{
if (nexitfuncs >= NEXITFUNCS)
return -1;
exitfuncs[nexitfuncs++] = func;
return 0;
}

which adds your function to the cleanup list, and cleanup(), in the same
file, after fetching and testing and, if appropriate, calling sys.exitfunc,
does:

while (nexitfuncs > 0)
(*exitfuncs[--nexitfuncs])();

[ I've never actually used that function myself, so someone, correct
me if I'm wrong, but it looks plain enough in the source code. ]

---| Steven D. Majewski (804-982-0831) <sdm7g@Virginia.EDU> |---
---| Computer Systems Engineer University of Virginia |---
---| Department of Molecular Physiology and Biological Physics |---
---| Box 449 Health Science Center Charlottesville,VA 22908 |---