POSIX Shared Memory writing/reading
I'm going over the POSIX shared memory section of this text book. I
couldn't get the code from the book to compile until I made a few changes.
I understand the idea of shared memory and how to open it, but I'm still
confused on the read/write. The text book code showed a hello world string
example, but I'm not sure how to apply it to ints, arrays, structs etc.
Here is the text book code I'm working with. Here is the write.
const int SIZE = 4096;
const char *name = "OS";
const char *message_0 = "Hello";
const char *message_1 = "World!";
int shm_fd;
void *ptr;
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, SIZE);
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
//sprintf(ptr, "%s", message_0); //non working text book code
sprintf((char*)ptr, "%s", message_0); //my change to get it to work
ptr += strlen(message_0);
//sprintf(ptr, "%s", message_1);
sprintf((char*)ptr, "%s", message_1);
ptr += strlen(message_1);
And here is the read.
const int SIZE = 4096;
const char *name = "OS";
int shm_fd;
void *ptr;
shm_fd = shm_open(name, O_RDONLY, 0666);
ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
printf("%s", (char*)ptr);
shm_unlink(name);
I tried changing this to write/read ints, but I couldn't get it to work. I
was under the impression that I should be able to do something for ints
like:
*ptr = 2;
ptr++;
But, I couldn't get that, or any other way I tried to work. Can anyone
explain it better? Thanks.
No comments:
Post a Comment