Reputation: 1
I am trying to run program with shared memory. My code as below.
Producer:
int main() {
const int SIZE = 4096;
const char *name="OS";
const char *message_0="Hello";
const char *message_1="World";
int fd;
char *wsk;
fd=shm_open(name,O_CREAT | O_RDWR, 0666);
ftruncate(fd,SIZE);
wsk=(char *)
mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd , 0);
sprintf(wsk,"%s",message_0);
wsk += strlen(message_0);
sprintf(wsk,"%s",message_1);
wsk += strlen(message_1);
return 0; }
Consumer:
int main(){
const int SIZE=4096;
const char *name= "OS";
int fd;
char *wsk;
fd=shm_open(name,O_RDONLY,0666);
wsk=(char *)
mmap(0,SIZE,PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
printf("%s", (char *)wsk);
shm_unlink(name);
return 0; }
But I am getting segmention fault. I think it can be problem with pointers but I can't find resolve.I am using macOs.Thanks in advance.
Upvotes: 0
Views: 113
Reputation: 11
The reason for the consumer exiting with a segmentation fault is due to permissions.
fd
is opened with O_RDONLY
(read only), whereas mmap
is called on fd with PROT_READ | PROT_WRITE
. This causes mmap
to error with EACCESS
(permission denied). When a function like mmap errors, it returns a negative number. This means when you try to print wsk
, you are trying to print a string at memory address -1
which obviously is not possible.
Upvotes: 1