Reputation: 13
I have created a struct in C. Now I want to write some data in that struct and want other process to read it. Let call the writer be server and reader be client.
For writer code goes like:
typedef struct
{
pthread_mutex_t mutex;
char * data;
} shm_data_struct, *shm_data_struct_t;
int shmid;
char * shm_address;
shm_data_struct_t shm_ptr;
int main(int argc, char const *argv[])
{
shmid = shmget(KEY, sizeof(shm_data_struct), IPC_CREAT | 0666)
shm_address = shmat(shmid, (void*)0, 0)
shm_ptr = (shm_data_struct_t)shm_address;
//Writing into struct
shm_ptr->data = "String";
while(shm_ptr->data != '*'){
sleep(1);
}
}
For the client Side:
typedef struct
{
pthread_mutex_t mutex;
char * data;
} shm_data_struct, *shm_data_struct_t;
int main(int argc, char const *argv[])
{
int shmid;
key_t key;
char *shm;
shm_data_struct_t shm_ptr;
key = 120;
shmid = shmget(key, sizeof(shm_data_struct), 0666)
shm = shmat(shmid, NULL, 0)
/*
* Now read what the server put in the memory.
*/
shm_ptr = (shm_data_struct_t)shm;
printf("%s\n", shm_ptr->data);
shm_ptr->data = '*';
exit(0);
}
This code is giving me segmentation fault in print statement in client's code. Can anybody help what I am doing wrong?
Upvotes: 0
Views: 815
Reputation:
This is your problem:
char * data;
Only the pointer (that is, an address) is being stored in shared memory. The data pointed to by the pointer is not shared, and the pointer itself will be invalid, or will point to unexpected data, in another process.
Generally speaking, SysV shared memory is a poor form of IPC, and should usually be avoided. As you've discovered, it cannot easily store even moderately complex data structures; it is also prone to race conditions, and the locking structures used to avoid that (i.e, SysV semaphores) will often create deadlocks if a process using them crashes.
Upvotes: 1