3

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.

  • 1
    Check answer [here](http://stackoverflow.com/questions/4879294/c-static-variables-and-linux-fork) – Chikei Mar 03 '12 at 11:13
  • MyClass is not instantiated before the fork but after so the link does not answer my question. I assumed the static variable should therefore always be initialized with an empty string, which is not always the case. How is that possible? –  Mar 03 '12 at 11:24
  • What do you mean by "fork"? There's no such thing in the C++ standard. If you are referring to some other platform/library, you must say so. – Kerrek SB Mar 03 '12 at 11:33
  • 1
    Fork as in the `fork()` system call –  Mar 03 '12 at 11:36
  • 1
    You assumed correctly, as [this test](http://ideone.com/fJ9vh) demonstrates. The result you describe cannot follow from the circumstances you describe. Please post a short program that demonstrates the problem. http://sscce.org/ – Robᵩ Mar 03 '12 at 20:23
  • Thanks Rob for the confirmation. I will need to investigate more as to what is happening exactly. –  Mar 03 '12 at 21:34

2 Answers2

3

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.

3

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.

qdii
  • 12,505
  • 10
  • 59
  • 116