Reputation: 426
I want to have a parent process which creates a bunch of children processes and I want all of them to operate (do read and write operations) on one buffer.
To clarify, by "buffer" I mean a C-string (null-terminated string) and what I want is... for instance if "cat" is stored in my buffer and child0 modifies this into "cat-cat", child1 and child2 and so on will also see the contents of the buffer as being "cat-cat".
There seems to be a command, mmap
which does exactly what I want but I have seen many guides on the internet but the thing is I have a very hard time wrapping my mind around shared zones of memory so I really need a concrete example of how to use it for what I need and none of the guides I've seen seem to properly cover this (most of them only cover read access and the ones that cover write access seem to be applicable for more complicated situations and therefore have complicated code which I don't really understand). So please keep this in mind if you're going to mark this as duplicate.
To further clarify and simplify my question... if I have $char *buf$ ... in my parent program.. what are the instructions of code that I need to write so that by writing $strcpy(buf, "cat")$ ... in one of my child processes, the change would be visible to all children processes?
Upvotes: 2
Views: 1735
Reputation: 18420
As you suspected, you can set up a shared memory space with mmap before fork()
-ing the child processes for that purpose:
#include <sys/mman.h>
char *shared_mem = mmap(NULL, MEMSIZE, PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANONYMOUS, -1, 0);
Now, this mapping is shared between all processes and modifications by one will be reflected in the others.
Upvotes: 3