C - shared memory - dynamic array inside shared struct

前端 未结 5 1673
攒了一身酷
攒了一身酷 2020-12-09 17:50

i\'m trying to share a struct like this
example:

typedef struct {
    int* a;
    int b;
    int c;
} ex;

between processes, the prob

5条回答
  •  一整个雨季
    2020-12-09 18:41

    The memory you allocate to a pointer using malloc() is private to that process. So, when you try to access the pointer in another process(other than the process which malloced it) you are likely going to access an invalid memory page or a memory page mapped in another process address space. So, you are likely to get a segfault.

    If you are using the shared memory, you must make sure all the data you want to expose to other processes is "in" the shared memory segment and not private memory segments of the process.

    You could try, leaving the data at a specified offset in the memory segment, which can be concretely defined at compile time or placed in a field at some known location in the shared memory segment.

    Eg: If you are doing this

    char *mem = shmat(shmid2, (void*)0, 0);

    // So, the mystruct type is at offset 0.
    mystruct *structptr = (mystruct*)mem;
    
    // Now we have a structptr, use an offset to get some other_type.
    other_type *other = (other_type*)(mem + structptr->offset_of_other_type);
    

    Other way would be to have a fixed size buffer to pass the information using the shared memory approach, instead of using the dynamically allocated pointer.

    Hope this helps.

提交回复
热议问题