首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用apr_shm库指向结构中指针的指针

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

Stack Overflow用户
提问于 2014-04-30 14:23:36
回答 1查看 155关注 0票数 0

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

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

代码语言:javascript
复制
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)中分配了无法从其他进程读取的私有内存。(儿童httpd)

这是怎么回事?任何帮助都很感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-30 19:16:09

如果您使用Apache (例如worker ),它大量使用线程,那么这段代码可能会正常工作,因为所有线程都将彼此共享一个地址空间,以及它们的父进程共享一个地址空间。但是,它不会在重负载下工作(因为Apache将开始对每一组线程使用不同的进程),或者在prefork mpm下完全不能工作。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23390723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档