Lucas
Lucas

Reputation: 567

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.

Upvotes: 1

Views: 3343

Answers (1)

Kevin Hopps
Kevin Hopps

Reputation: 727

You can cast the mmap result to int* or double* or whatever you like. One thing you can do is to overlay a struct onto the shared memory:

struct MyStruct
{
    int s_int;
    char s_str[64];
};

void* mem = mmap ...
struct MyStruct* sp = (struct MyStruct*)mem;

/* writing */
sp->s_int = 3;
strcpy(sp->s_str, "Hello");

/* reading */
printf("s_int=%d, s_str=%s\n", sp->s_int, sp->s_str);

Upvotes: 4

Related Questions