指向使用apr_shm库的结构中的指针的指针

pointer to a pointer in a struct using apr_shm library

本文关键字:指针 shm 结构 apr      更新时间:2023-10-16

我在这里使用apr共享库获得了apache模块代码。

我修改为共享数据结构,添加一些具有指向指针的字段,等等。。

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;
    }   
}
...

而且效果很好。子进程可以访问指向的"dpp"或"str"的值。

据我所知,malloc在一个进程(父httpd(中分配了私有内存,该进程无法从其他进程读取。(child-httpd(

这是怎么回事?感谢您的帮助。

如果您使用的是大量使用线程的Apache MPM(如worker(,则此代码可能会出现,因为所有线程将彼此共享地址空间,并与其父进程共享地址空间。然而,它在重负载下无法工作(因为Apache将开始为每组线程使用不同的进程(,或者在preforkmpm下根本无法工作。

如果要将数据存储在共享内存中,所有数据都必须存储在共享存储器中(即,不能对任何数据使用malloc()(,并且不能在该内存中使用指针(因为如果shm区域映射到其他位置,指针将变为无效(。