C: How to transfer a structure (or, if possible, an array) between parent and child (forked) processes via IPC?

I have been looking for this in the last two weeks, and I have not received any response. This is what I have:

  • The parent process that creates the myStruct structure, which is basically a linked list using pointers (if this is a serious problem, I can accept using a fixed-size array instead).

  • A fixed number of child processes created using fork() that need read / write access to the structure (or array) created by the parent.

I do not know how to do this to make the exchange of the myStruct variable between processes.

I tried to solve the problem using SICV IPC functions like shmget() , shmat() etc. to allocate my variable in shared memory, but I don't know how to work with void memory pointers to read / write values โ€‹โ€‹in myStruct.

Ideally, I would like to be able to use dot notation (myStruct.node)->attribute = value in each process, without dealing with pointers, since I don't know how my structure is organized into memory.

Is it possible? Could some of you help? Any help is REALLY appreciated.

In addition, I know that using threads, pipes, sockets, or similar things would be much easier, but this work is for academic purposes, for which I must imitate the presence of several independent processes.

+4
source share
2 answers

If you create a general anonymous mapping using:

 p = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); 

Then these pages will not be copied to the record, but will be shared by all forked processes.

Please note that you must be careful with locking here. You can use the standard pthread and condvars mutexes in the shared memory segment between processes if (and only if!) You use pthread_mutexattr_setpshared and pthread_condattr_setpshared to mark them as shared between processes.

Note also that this method displays a fixed-size arena and must be performed before forking. How you manage the contents of memory in p up to you. This is not trivial to create a scalable arena of shared memory; if you want to go this route, I would recommend posting a second question, as different approaches may be required.

+2
source

The easiest way to exchange memory through a plug is to use the mmap() ed memory area. If you use anonymous mmap() (with MAP_ANON and MAP_SHARED) to store your structure (array, whatever) instead of malloc() ed memory, it will be passed by the child process.

0
source

Source: https://habr.com/ru/post/1338893/


All Articles