Are global variables static for child and parent processes?

Possible duplicate:
After forked shared globals?

In my C program, I store the structure-bound list as a global variable. Then I'll redo the child process. Now in the child process if I free the node of the linked list and then terminate the child process. Won't node be in the parent process?

When I tried to do this, it seems that the node was still present in the parent process ... Is this correct? Why?

+3


source to share


3 answers


No, it will not disappear in the parent process. The correct mental model is that the child receives an independent copy of the parental memory. These two processes do not share memory (unless you explicitly create a shared memory segment and place your data there).



The situation is radically different if you use threads instead of processes. Threads running in the same process share the address space.

+9


source


fork(2)

creates a copy of the parent's virtual address space, so unless you put these struct

in shared memory, they are completely unrelated.



+2


source


Yes, it works as intended, you cannot change parent from child (or child from parent)

The two processes (parent and child) are two different processes and just like one of your processes cannot write to the memory of, say, a web server that is also running on your computer, the parent process can "t write to the child process or vice versa.

To avoid having to copy EVERYTHING in the parent process to the child process, the OS uses something called "copy-on-write", which works like this: when the "child" process is running, the pages representing the parent process are duplicated and marked as "only for reading". When a write occurs, the OS traps it, which writes (which is invalid because the memory is read-only) and creates a copy of the memory, so that the process of writing to memory is like its own copy of memory [and unchecks the read-only mark for another process. so it can now modify the data since it has the original memory contents].

As others have said, you can overcome this by using "shared memory" (which can also be shared between completely independent processes if you like).

+1


source







All Articles