Question

I have a count variable that should get counted up by a few processes I forked and used/read by the mother process.

I tried to create a pointer in my main() function of the mother process and count that pointer up in the forked children. That does not work! Every child seems to have it's own copy even though the address is the same in every process.

What is the best way to do that?

Was it helpful?

Solution

Each child gets its own copy of the parent processes memory (at least as soon as it trys to modify anything). If you need to share betweeen processes you need to look at shared memory or some similar IPC mechanism.

BTW, why are you making this a community wiki - you may be limiting responses by doing so.

OTHER TIPS

2 processes cannot share the same memory. It is true that a forked child process will share the same underlying memory after forking, but an attempt to write to this would cause the operating system to allocate a new writeable space for it somewhere else.

Look into another form of IPC to use.

My experience is, that if you want to share information between at least two processes, you almost never want to share just some void* pointer into memory. You might want to have a look at

Boost Interprocess

which can give you an idea, how to share structured data (read "classes" and "structs") between processes.

No, use IPC or threads. Only file descriptors are shared (but not the seek pointer).

You might want to check out shared memory.

the pointers are always lies in the same process. It's private to the process, relative to the process's base address. There different kind of IPC mechanisms available in any operating systems. You can opt for Windows Messaging, Shared memory, socket, pipes etc. Choose one according to your requirement and size of data. Another mechanism is to write data in target process using Virtual memory APIs available and notify the process with corresponding pointer.

One simple option but limited form of IPC that would work well for a shared count is a 'shared data segment'. On Windows this is implemented using the #pragma data_seg directive.

See this article for an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top