7.8. Registered Cleanups

Although the logging phase is the last official phase of the request cycle, there is one last place where modules can do work. This is the cleanup phase, during which any code registered as a cleanup handler is called to perform any per-transaction tidying up that the module may need to do.

Cleanup handlers can be installed in either of two ways. They can be installed by calling the request object's register_cleanup( ) method with a reference to a subroutine or method to invoke, or by using the PerlCleanupHandler directive to register a subroutine from within the server configuration file. Here are some examples:

# within a module file
 $r->register_cleanup(sub { warn "server $$ done serving request\n" });

 # within a configuration file
 PerlModule         Apache::Guillotine  # make sure it's loaded
 PerlCleanupHandler Apache::Guillotine::mopup()

There is not actually a cleanup phase per se. Instead, the C API provides a callback mechanism for functions that are invoked just before their memory pool is destroyed. A handful of Apache API methods use this mechanism underneath for simple but important tasks, such as ensuring that files, directory handles, and sockets are closed. In Chapter 10, you will see that the C version expects a few more arguments, including a pool pointer.

There are actually two register_cleanup() methods: one associated with the Apache request object and the other associated with the Apache::Server object. The difference between the two is ...

Get Writing Apache Modules with Perl and C now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.