tl;dr: How I can I configure cJSON to allocate memory in child processes, so that the parent can see the resulting structs?
I have a request that comes in that lists multiple products for which summaries are to be generated and returned as JSON. Currently, my code is single-threaded and uses the cJSON library for composing and marshalling the JSON.
As the summaries are computationally expensive (user requests certain calculations to be performed as part of the summaries), I'd like to fork(2)
for each requested product, then have it fetch, process, and summarise into cJSON_Object
( technically cJSON*
but the "constructor" is cJSON_CreateObject
), and then have the parent thread wait for all children to return their cJSON_Object
objects to join together, perform some post processing, and then finally marshall into a string to return. Because of post-processing, I'd like to return to the parent a cJSON_Object
rather than have the child threads return strings.
Now, I see cJSON.h:144 CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks)
which accepts a cJSON.h:125 struct internal_hooks
which allows you to specify custom malloc()
and free()
implementations... which would be peachy if I could find a versions that allocate shared memory... and share the same type. The closest I found was shmalloc
/shfree
but that's from the OpenMPI library and just seems like overkill for what seems like it should be simple worker threads...
Now, this is where I am stuck, how do I return a graph of cJSON structs from child processes to the parent?
I've attached the best (albeit untested) solution I've thought of as an answer to not clutter this question further.
PS - Preferably the solution would restrict itself to the POSIX API, but Linux-only is acceptable, and additional libraries as a last resort.