Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a structure with pointers between two unrelated processes with shared memory in C?

I have a structure which looks like:

typedef struct shared_data_t
{
    char *key;
    char *message;
}shared_data;

I need to share this structure with another unrelated process. I am using POSIX shared memory with shm_open()/mmap() to achieve this. However, my target process is not getting the shared data and its dieing with SIGSEGV, which is obvious. It will be great if someone help me on this, specially what happens while sharing pointers between two processes with shared memory (with shm_open and mmap).

For a structure like,

typedef struct shared_data_t
{
    char key[8];
    char message[32];
}shared_data;

it works all fine!

like image 490
Saurav Haloi Avatar asked Mar 21 '23 13:03

Saurav Haloi


1 Answers

There is a note about this in the Linux man page for shmat:

       Using shmat() with shmaddr equal to NULL is the preferred, portable way
       of attaching a shared memory segment.  Be aware that the shared  memory
       segment  attached in this way may be attached at different addresses in
       different processes.  Therefore, any  pointers  maintained  within  the
       shared  memory must be made relative (typically to the starting address
       of the segment), rather than absolute.
like image 194
Vaughn Cato Avatar answered Mar 23 '23 03:03

Vaughn Cato