tags:

views:

650

answers:

7

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?

+11  A: 

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.

anon
Okay. Thank you! I was expecting something like this. Could you please tell me why I got the same address in every process? Shouldn't that differ because the memory was copied?
Lennart
No, because what you see are virtual memory addresess, not real ones.
anon
Okay! Thank you again. :) I did not know that community wikis don't generate reputation. Just read that in the FAQ. Sorry!
Lennart
A: 

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

Johannes Weiß
+1  A: 

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.

MattJ
A: 

You might want to check out shared memory.

none
A: 

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.

Sarath
A: 

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.

Rob Walker
+1  A: 

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.

primeMover