我使用apr共享库here获取了apache模块代码。
我修改为共享数据struct添加一些具有指针指针的字段,依此类推......
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)
这是如何工作的?任何帮助表示赞赏。