I wanted to write some function void* share(void*, int) , which should set up shared memory for sharing data in a pointer.
My first attempt looked (without checks, etc.):
void* share(void *toBeShared, int size) { int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR); ftruncate(fd, size); return mmap(toBeShared, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); }
but that doesn't seem to work as I would like. The second attempt was something like this:
void* share(void *toBeShared, int size) { void *mem = NULL; int fd = shm_open(SHM_NAME, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR); ftruncate(fd, size); mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0) memcpy(mem, toBeShared, size); return mem; }
and it really works, but I need to copy all the data that I would like to avoid.
So my question is: is there a way to split the memory that has already been allocated (if possible, without having to copy too much), and if so, how can this be done?
Thanks in advance.
PS: I saw more of these questions (for example, here and here ), but there are no answers to them.
edit:
how i would like to use it:
typedef struct { char *name; int status; } MyTask; int main(int argc, char** argv) { MyTask* taskList = NULL, sharedTaskList = NULL; int length = 0; ... readFile(&taskList, &length, ...); sharedTaskList = share(taskList, length * sizeof(MyTask));