Question

I got the apache module code using apr shared library here.

And I modified to shared data struct add some field that has pointer to a pointer, and so on like this..

typedef struct {
    int a;
    int b;
    char *str;
    double **dpp;
    STRU1 **str;
} shm_data;

/* The per-server configuration */
typedef struct {
    char *shmcounterfile;
    char *shmcounterlockfile;
    apr_global_mutex_t *mutex; /* the cross-thread/cross-process mutex */
    apr_shm_t *data_shm;   /* the APR shared segment object */
    shm_data *data;  /* the per-process address of the segment */
} shm_data_scfg_t;

...

/* parent httpd init code => ap_hook_post_config */
scfg = (shm_data_scfg_t*)ap_get_module_config(s->module_config, &shm_module);

apr_shm_create(&scfg->data_shm, sizeof(*scfg->data),
                            scfg->shmcounterfile, pconf);
/* The pointer to the shm_data structure is only valid
 * in the current process, since in another process it may
 * not be mapped in the same address-space. This is especially
 * likely on Windows or when accessing the segment from an
 * external process. */
scfg->data = (shm_data*)apr_shm_baseaddr_get(scfg->data_shm);

/* Clear all the data in the structure. */
memset(scfg->data, 0, sizeof(*scfg->data));

scfg->data->a = 1;
scfg->data->b = 2;
scfg->data->str = "test";

scfg->data->dpp = (double**)malloc(sizeof(double*) * 10);
for (int i = 0; i < 10; i++) {   
    scfg->data->dpp[i] = (double*)malloc(sizeof(double) * 10);
    for (int l = 0; l < 10; l++) {   
        scfg->data->dpp[i][l] = l;
    }   
}
...

And it works fine. Child processes can access the values of 'dpp' or 'str' pointed are same as it is.

As far as i know malloc'd allocated private memory in a process(parent httpd) that can't read from other process. (child httpd)

How does this work? Any help appreciated.

Was it helpful?

Solution

It's possible that this code may appear to work if you are using an Apache MPM such as worker which uses threads heavily, since all of the threads will share an address space with each other, as well as with their parent process. However, it will not work under heavy load (as Apache will start to use different processes for each set of threads), or at all under the prefork mpm.

If you want to store data in shared memory, all of the data must be stored in shared memory (i.e, you cannot use malloc() for any of it), and you cannot use pointers within that memory (since they will become invalid if the shm region is mapped to a different location).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top