I'm developing an Apache 2 module. Why is create_server_config is called twice when the service starts up?

StackOverflow https://stackoverflow.com/questions/14620479

Question

I wrote the module code like this:

static void *example_create_server_config(apr_pool_t *p, server_rec *s)
{
  syslog(LOG_ERR, "create_server_config");
  // create my handler
  // my_handler_t *handler = (my_handler_t *)apr_palloc(pool, sizeof(my_handler_t));
  return NULL;
}

/* Dispatch list for API hooks */ 
module AP_MODULE_DECLARE_DATA example_module = {
    STANDARD20_MODULE_STUFF,
    NULL,                               /* create per-dir    config structures */
    NULL,                               /* merge  per-dir    config structures */
    example_create_server_config,       /* create per-server config structures */
    NULL,                               /* merge  per-server config structures */
    example_cmds,                       /* table of config file commands       */
    example_register_hooks              /* register hooks                      */
};

When I restart Apache, the /var/log/syslog contains this:

Jan 31 14:46:49 su02 apache2: create_server_config
Jan 31 14:46:49 su02 apache2: create_server_config
Jan 31 14:46:49 su02 apache2: child_init

Why is the create_server_config function be called twice?

I malloc some global variables in this function. Is that safe or not?

Was it helpful?

Solution

It is perfectly safe to acquire memory using the apr_pool_t pointer that you receive inside of this function. Also, this function will be invoked once for every server/host configuration you have in your httpd.conf file, so that's why you see multiple calls to this function. For example a root server configuration and one configuration section would make this function be invoked twice.

typedef struct
{
    int value;
} my_srv_cfg;

static void *example_create_server_config(apr_pool_t *pool, server_rec *s)
{
    my_srv_cfg *new = apr_pcalloc(pool, sizeof (*new));
    new->value = 100;
    return new; 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top