Welcome! Log In Create A New Profile


Re: ngx_http_cleanup_add

Maxim Dounin
November 10, 2021 10:48PM

On Wed, Nov 10, 2021 at 07:22:50PM -0800, Dk Jack wrote:

> Hi,
> In my module, I am allocating some memory for each request and saving the
> ptr in my module context. I am registering a callback using
> ngx_http_cleanup_add to perform cleanup for each request. I am releasing
> the memory for the allocation in the cleanup callback. In the log phase, I
> want to make available the contents of the memory I allocated as an nginx
> variable.
> However, when I try to print this variable in the log, the memory has
> already been de-allocated. It looks like the clean-up handlers are called
> before the log phase. Since I have released the memory in the cleanup
> handler, I have nothing to log in the log phase. Is there a way to defer
> the calling of the clean-up handler until after the log phase?

Request cleanup handlers as allocated by ngx_http_cleanup_add()
are expected to be called before logging: these are used to stop
various activities which might still be going on when nginx
decides to terminate the request. Notably, it used by the
upstream module to close upstream connections.

If you want to free the memory, a better idea would be to use pool
cleanup handlers instead, which are registered by the
ngx_pool_cleanup_add() function. These are called while actually
freeing request memory, after all request processing is completely
finished, including logging. See here for details:


Note well that for per-request allocations it is usually better to
simply allocate memory from the request pool via ngx_palloc(), so
it is freed automatically when the request pool is destroyed.
Pool cleanup handlers are mostly needed to free various external
resources, such as file descriptors or memory from external

Maxim Dounin
nginx-devel mailing list
Subject Author Views Posted


dnj0496 377 November 10, 2021 10:24PM

Re: ngx_http_cleanup_add

Maxim Dounin 152 November 10, 2021 10:48PM

Re: ngx_http_cleanup_add

dnj0496 165 November 10, 2021 11:04PM

Sorry, you do not have permission to post/reply in this forum.

Online Users

Guests: 83
Record Number of Users: 6 on February 13, 2018
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready