开发者

C language: How to share a struct (or, if not possible, an array) between parent and child (forked) processes through IPC?

开发者 https://www.devze.com 2023-02-09 12:59 出处:网络
I googled this for the past two weeks and I didn\'t get any answer. This is what I have: A parent process, which creates a struct myStruct that is basically a linked list using pointers (if this is

I googled this for the past two weeks and I didn't get any answer. This is what I have:

  • A parent process, which creates a struct myStruct that is basically a linked list using pointers (if this is a major issue, I can accept to use a fixed size array instead).

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

I don't know how to do in order to make the variable myStruct become shared between processes.

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

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

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

Further note: I know using threads, pipes, sockets or things like that would be much easier, but this work is for academic开发者_如何学Python purposes for which I have to simulate the presence of multiple independent processes.


If you create a shared anonymous mapping with:

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

Then these pages will not be copied-on-write, but rather will be shared by all forked processes.

Note that you have to be careful with locking here. You can use standard pthread mutexes and condvars on 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 technique maps a fixed size arena, and must be done before forking. How you manage the contents of the memory at p is up to you. It's nontrivial to create a resizable shared memory arena; if you want to go that route, I'd recommend posting a second question, as different approaches may be necessary.


The easiest way to share memory across a fork is to use a mmap()ed region of memory. If you use an anonymous mmap() (with MAP_ANON and MAP_SHARED) to store your struct (array, whatever) instead of malloc()ed memory, it will be shared by the child process.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号