I know the fork()
function creates a process which is identical to its parents, only differs by the PID it has. They have the same variables initially, and changes made to these variables do not affect each other. But what happens when a global pointer variable is shared?
I have written some code and printed out the results. It appears that the parent and the child process have the pointer pointing to the same memory location, however changes made to these memory locations, i.e. *p = 1
in parent and *p = 2
in child, do not affect each other. Also note that I make the parent process wait(NULL)
until the child process exits. So the child process changes the value pointed by the pointer having the same memory address of the parent process' pointer.
I know when fork()
is called, parent process clone everything: registers, program counters etc. But how is that possible? Shouldn't the parent process have its variable's value changed after the child process exits? Is it due to the system puts everything (including the parent process' pointer variable's) onto stack and pops them when the child is terminated?