I'm using an array of structs for share data between two process. The program after 3 secs raise an Segmentation fault error, when I try to access to the shared memory into the parent process. Why the data is not correctly shared?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define LEN 3
typedef struct {
int val;
} val_t;
int
main (int argc, char *argv[])
{
key_t key;
int shmid, i, size;
val_t **val;
if ((key = ftok(argv[0], 'D')) == -1) {
perror("ftok");
exit(1);
}
size = sizeof(val_t *) * LEN;
if (fork() == 0) {
if ((shmid = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666)) == -1) {
perror("shmget");
exit(1);
}
val = (val_t **) shmat(shmid, 0, 0);
if (val == (val_t **)(-1)) {
perror("shmat");
exit(1);
}
for (i = 0; i < LEN; i++) {
val[i] = (val_t *) malloc(sizeof(val_t));
val[i]->val = i;
}
while (val[0]->val != 3)
sleep(1);
if (shmdt(val) == -1) {
perror("shmdt");
exit(1);
}
shmctl(shmid, IPC_RMID, NULL);
}
else {
sleep(3);
if ((shmid = shmget(key, size, IPC_EXCL)) == -1) {
perror("shmget");
exit(1);
}
val = (val_t **) shmat(shmid, 0, 0);
if (val == (val_t **)(-1)) {
perror("shmat");
exit(1);
}
printf("%d\n", val[0]->val);
val[0]->val = 3;
if (shmdt(val) == -1) {
perror("shmdt");
exit(1);
}
}
return 0;
}
struct". You have a pointer to pointer tostruct, but likely want a "pointer tostruct" according to your title. 2) Do not cast the result ofmalloc& friends in C. 3) Not sure, but ifvalis the shared array, why do you set the pointers to "private" memory? 4) You apparently have problems with the multiple indirection in various places.