CodeKingPlusPlus
CodeKingPlusPlus

Reputation: 16081

C static variables and forking processes

Suppose that I have a static variable initialized globally to zero and I have a process that forks. Now suppose that in this parent process the static variable is set to a value 10. I am noticing in the child process that the static variable is still zero. This behaviour is reasonable because we have not changed the value of this variable in the child process.

How can I get the static variable in the child to be the same value of this variable in the parent? That is, the child's copy of the static variable is also set to value 10.

Thanks and let me know if you need any more information.

Upvotes: 0

Views: 874

Answers (1)

abligh
abligh

Reputation: 25139

The short answer is that with a static variable you can't, as the memory area in which statics are allocated cannot be shared. Instead, you can create a shared memory area to do this. One way to do this is mmap with MAP_ANONYMOUS and MAP_SHARED. Think of it like malloc() except in page sized units. Another route is to use shm_open().

Upvotes: 1

Related Questions