简体   繁体   中英

Trouble writing into shared memory buffer in C

Let's say i have a buffer:

int * buffer;

and this buffer is shared with multiple processes (shared memory).

If i want to read/write from/to that buffer how would i do it?

I'm asking this because i found lot's of information and all sorts of different methods to solve this problem, but the answers lacked organisation, and became very confusing and difficult to understand.

Here's the function i used to create the shared memory segment:

void * create_shared_memory(char *name, int size) {

    int *ptr;
    int ret;

    int fd = shm_open (name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);

    if (fd == -1) { 
        perror ("shm_open error!");
        exit (1);
    }

    ret = ftruncate (fd, sizeof (size));

    if (ret == -1) {
         perror ("ftruncate error!");
         exit (2);
    }

    ptr = mmap(0, sizeof (size), PROT_READ | PROT_WRITE,  MAP_SHARED, fd, 0);

    if (ptr == MAP_FAILED) {
        perror ("shm-mmap error!");
        exit (3);
    }

return ptr;

}

Having created and mapped a shared memory segment, thereby obtaining a pointer to it, you read from or write to it via that pointer. As far as syntax and mechanics, this is the same as for any other memory. You can wrap functions around that any way you like, but you do not inherently need to do so.

As EOF observed, however, shared memory semantics are a lot more complicated than non-shared memory semantics. You need to use appropriate synchronization aids around shared-memory accesses to ensure that threads and/or processes cooperate properly, else the results are undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM