Reputation: 544
So I am making a program that will have multiple processes that all need to access a struct, 'node', that I have defined. So I initialize the memory as follows:
sharedMemory = (node*)malloc(sizeof(node));//sharedMemory is a global node
sharedMemory->syskey = sys_key;//just a variable from a function
segment_id = shmget(sharedMemory->syskey, size, S_IRUSR | S_IWUSR | IPC_CREAT);
sharedMemory = (node*)shmat(segment_id, NULL, 0);
And this seems to go fine. However I then need to access this piece of memory later. So what I tried to do was this:
segment_id = shmget(sharedMemory->syskey, size, S_IRUSR | S_IWUSR | IPC_CREAT);
sharedMemory = (node*)shmat(segment_id, NULL, 0);
And then use sharedMemory. However when I did this everything in sharedMemory seems to have been reset to 'null' (arrays and such). I am sure that I am just doing something stupid but the documentation is a bit confusing for me. Any help would be appreciated.
Upvotes: 1
Views: 115
Reputation: 544
I figured out that I was doing it correctly except for the fact that sharedMemory was a global variable. I needed to just re-declare this whenever I called shmat and attach it. Seems to be working now.
Upvotes: 1