简体   繁体   中英

C shared memory passing structure in structure

I'm making a Dns server and ran into a issue while doing it So I have to pass a structure within a structure using for that shared memory. I start by doing this in the parent process:

if((shmid=shmget(IPC_PRIVATE,sizeof(shared_mem),IPC_CREAT | 0777))<0){ 
    perror("Error in shmget\n");
    exit(1);
}
#ifdef DEBUG
else{
    puts("Segmento alocado com sucesso.\n");
}
#endif

//ataches memory to address
if((s_m = (shared_mem*) shmat(shmid,NULL,0)) ==(shared_mem*) -1){
    perror("Error in shmat\n");
    exit(1);
}
#ifdef DEBUG
else{
    puts("Memoria conectada ao adereço com sucesso.\n");
}

then,I declare my variable like this:

s_m->dataUltimoPedido=(tempo*) malloc(sizeof(tempo));
s_m->dataUltimoPedido=(tempo*) buscadata();

being buscadata()

tempo* buscadata(){
    tempo* busca;
    busca=(tempo*)malloc(sizeof(tempo));
    time_t rawtime;
    struct tm *tminfo;
    time ( &rawtime );
    tminfo = localtime ( &rawtime );
    busca->hora=tminfo->tm_hour;
    busca->min=tminfo->tm_min;
    busca->mes=(tminfo->tm_mon)+1;
    busca->ano=(tminfo->tm_year)+1900;
    busca->dia=tminfo->tm_mday;
    return busca;
}

each time there is a request i do this:

s_m->dataUltimoPedido=(tempo*) buscadata();

and in this process it works. But in a child process that runs every 30 seconds I try to access it like this:

shared_mem* s_m;
s_m =(shared_mem*) shmat(shmid, NULL, 0);

while(1){
    printf("%d---------------------\n",s_m->dataUltimoPedido->hora);
}

this always prints 0,and i have no idea why.It works for simple variables but not for this structure,any ideas why?

You cannot share a pointer returned by malloc() between two processes. If you do something like:

void buscadata(tempo* busca){
    time_t rawtime;
    struct tm *tminfo;
    time ( &rawtime );
    tminfo = localtime ( &rawtime );
    busca->hora=tminfo->tm_hour;
    busca->min=tminfo->tm_min;
    busca->mes=(tminfo->tm_mon)+1;
    busca->ano=(tminfo->tm_year)+1900;
    busca->dia=tminfo->tm_mday;
}

Change the definition of shared_mem so that dataUltimoPedido is a tempo rather than a tempo* . Then call this function like:

buscadata(&s_m->dataUltimoPedido);

It should directly populate this structure within your shared memory segment and the child process should see the changes.

The bottom line is that anything that is actually written directly to the shared memory segment will be seen by the child process. Pointers within the shared memory segment that point to things outside the shared memory segment won't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM