I am trying to understand the System V shared memory APIs. I created a small program where one writes into the shared memory and another reads from the shared memory. But for some reason, I am getting an error :
segmentation fault: 11
as I try to read from the shared memory. I could not find the reason for it.
Here is what I have done:
The following program writes into the shared memory.
#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> struct shm_seg { char *buf; }; int main() { int shmid = shmget(1, sizeof(struct shm_seg), IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if(shmid == -1) { printf("Failed to fetch the shared memory id"); exit(-1); } struct shm_seg *shm_segp = shmat(shmid, NULL, 0); if(shm_segp == (void*)-1) { printf("Failed to attach shared memory to the shared memory id"); exit(-1); } while (1) { shm_segp->buf = "hello"; } if(shmdt(shm_segp) == -1) { printf("Failed to detach the shared memory"); exit(-1); } if(shmctl(shmid, IPC_RMID, 0) == -1) { printf("Failed to delete a shared memory object"); exit(-1); } }
and the following code attempts to read from the shared memory.
#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> struct shm_seg { char *buf; }; int main() { int shmid = shmget(1, 0, 0); if(shmid == -1) { printf("Failed to fetch the shared memory id"); exit(-1); } struct shm_seg *shm_segp = shmat(shmid, NULL, SHM_RDONLY); if(shm_segp == (void*)-1) { printf("Failed to attach shared memory to the shared memory id"); exit(-1); } int i = 0; while(i < 100 ) { printf("%sn",shm_segp->buf); i++; } if(shmdt(shm_segp) == -1) { printf("Failed to detach the shared memory"); exit(-1); } }
The above reader program results in a Segmentation fault: 11
error. What could be the reason for this? What is it that I am doing wrong?
Advertisement
Answer
shm_segp->buf = "hello";
That code makes no sense. This puts a pointer in shared memory.
Your code passes a pointer to a string constant from one program to the other. Then it dereferences that pointer in the other program. But what sense does that make? It’s a pointer into the other program’s memory space that means nothing to a different program.
If you want to pass data from one program to another, you need to actually put the data you want to pass in shared memory. Putting a pointer to it in shared memory won’t do any good if the data itself isn’t in shared memory!