My problem is that if a client makes a change in the struct the next one won't be able to know.
As you noted, mmap()
is part of the solution...
Shared memory needs of your application can be addressed with _shm_open()_, _shm_unlink()_, mmap etc. as illustrated in this post. And here for additional examples on shared memory
All of the essentials are summarized in the links, but this excerpt describes the basic concept:
shm_open() creates and opens a new, or opens an existing, POSIX
shared memory object. A POSIX shared memory object is in effect a
handle which can be used by unrelated processes to mmap(2) the same
region of shared memory. The shm_unlink() function performs the
converse operation, removing an object previously created by
shm_open().
I also wanted to suggest that dynamic allocation of memory may be of use in creating space for your struct
on an as-needed basis. The size of members, as shown are excessively large,
char keys[4096];
char values[4096];
but in comments you state they only need to be 51 bytes. The struct then can be created as a typedef:
struct keyvalue {
char keys[51];
char values[51];
} DATA;
The create an instance of a pointer to your struct:
DATA *pData = {0};
Which can then be sized on an as needed basis using standard malloc, and or realloc
pData = malloc(initialSize*sizeof(DATA));
As size requirements change, use the following to grow memory:
DATA *tmp = {0};
tmp = realloc(pData, newSize);
if(!tmp) return -1;//ensure memory allocation successful
pData = tmp;//tmp includes previous contents of pData, and more space
... //continue using pData
Free pData when it is no longer needed.
free(pData);
To pass this struct in a function, the function might look like this:
void func1(DATA *d, int numElements)
{
...
for(i=0;i<numElements;i++)
{
strcpy(d[i]->keys, "some key");
strcpy(d[i]->values, "some value");
}
...
}
To call that function with a copy of pData
, if say it had a 1000 elements:
func1(pData, 1000);