3

Possible Duplicate:
After forking, are global variables shared?

In my C program, I keep a struct linked list as a global variable. Then later I fork a child process. Now in the child process if I free a node of the linked list, and then end the child process. Will the node be gone in the parent process as well?

When I was trying this, it seems the node was still there in the parent process... Is this right? Why?

Community
  • 1
  • 1
omega
  • 40,311
  • 81
  • 251
  • 474

3 Answers3

9

No, it won't be gone in the parent process. The correct mental model is that the child is getting an independent copy of the parent's memory. The two processes are not sharing the memory (not unless you explicitly set up a shared memory segment and place your data there).

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

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Is there a way to keep things static to both child and parent? – omega Jan 23 '13 at 21:12
  • Yes. Shared memory. The memory is *shared* between processes, in this case the parent and child. And you would require some synchronization mechanism if both processes change the data. – Duck Jan 23 '13 at 21:15
  • @NPE maybe you should stress _independent_ copy. Update: Right now you're facing a law suite from Apple – stefan Jan 23 '13 at 21:15
  • @stefan, what's this about Apple? More insane patent or copyright law? – Duck Jan 23 '13 at 21:30
2

fork(2) creates a copy of parent virtual address space, so unless you place these structs into shared memory, they are totally unrelated.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
1

Yes, it works as intended, you can't modify the parent from a child (or the child from the parent)

The two processes (parent, and child) are two different processes, and just like one of your process can't write into the memory of, say, a webserver that is also running on your machine, the parent process can't write to the child process or vice versa.

To avoid having to copy EVERYTHING in the parent process into the child process, the OS uses something called "copy-on-write", which works like this: When a "child" process is made, the pages representing the parent process are duplicated, and marked "read-only". When a write happens, the OS traps that write (which is not allowed, because the memory is read-only), and makes a copy of the memory, so that the process writing to memory as its own copy of the memory [and unmarks the "read-only" on the other process, so it can now modify the data, as it has the original memory content].

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

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227