C ++: Is it possible to use a pointer through forked processes?

I have a variable called count, which should be counted by several processes that I forked and used / read the parent process.

I tried to create a pointer in my main () function of the mother process and count this pointer up in forked children. This does not work! It seems that each child has his own copy, although the address is the same in every process.

What is the best way to do this?

+4
source share
7 answers

Each child receives its own copy of the memory of the parent processes (at least as soon as it tries to change something). If you need to separate different processes, you need to look at shared memory or some other IPC mechanism.

By the way, why are you creating this wiki community - you can limit the answers by doing this.

+15
source

2 processes cannot use the same memory. It is true that a forked child process will share the same base memory after forking, but attempting to write this will cause the operating system to allocate a new recording location elsewhere.

Look at another form of IPC to use.

+2
source

My experience is that if you want to exchange information between at least two processes, you almost never want to share some void * pointer in memory. Maybe you should take a look at

Enlarge Interprocess

which can give you an idea of โ€‹โ€‹how to distribute structured data (read "classes" and "structures") between processes.

+1
source

No, use IPC or streams. Only file descriptors are shared (but not search pointers).

0
source

You might want to check shared memory.

0
source

pointers always lie in the same process. It is private to the process, relative to the base address of the process. Different operating systems have different IPC mechanisms available. You can choose Windows Messaging, shared memory, socket, channels, etc. Choose one according to your requirements and data size. Another mechanism is to write data to the target process using the available virtual memory APIs and notify the process with an appropriate pointer.

0
source

One simple option, but a limited form of IPC that will work well for a shared account, is a โ€œshared data segmentโ€. On Windows, this is implemented using the #pragma data_seg .

See an example article for an example.

0
source

All Articles