user1047621
user1047621

Reputation:

C++ static variable and multiple processes

I have a C++ program which forks child processes to do some work. In these child processes some classes are created and there is a static variable inside a member function like so:

void MyClass::foo () {
    static std::string uuid;
    ...
    uuid = "A new value";
}

Since each process is freshly forked, I assumed uuid to always be initialized as an empty string. However, in some cases I noticed the uuid already has been given a value upon the first entry of the function, which causes problems.

How can this static variable be initialized across forked processes? And is my only option to use an class variable? The reason for the static variable is that I didn't want to introduce class variables which are only used inside a single function so to keep the class nice and tidy.

Upvotes: 3

Views: 5112

Answers (2)

qdii
qdii

Reputation: 12963

When the first process is started, the binary executable is mapped in memory, and its different sections all end up in memory (.bss, .text, etc.). As the data section is mapped in memory, your static variable points to an offset of the mapped .data section.

Now when a process forks, the created process is granted its own virtual memory space, which is a perfect copy of its parent’s (at the time of forking). The "uuid" points to its own memory zone.

Side note: the kernel allows the children’s virtual pages to map to the same physical pages as the parents, as longs as they are none of the two processes modify them.

Upvotes: 3

user1047621
user1047621

Reputation:

I found out MyClass is also instantiated in the parent process in rare situations. After that, forked processes inherit the static variable which is already initialized with a value in the parent process.

Upvotes: 3

Related Questions