I am trying to understand the fork() concept and there's is one thing I can't seem to understand.
In the following code - why does the parent still print i=0 even when child process changes it to 5?
The wait(NULL) blocks parent process until child finishes first.
int main(int argc, char *argv[]) {
int i = 0;
if (fork() == 0) {
i = 5;
} else {
wait(NULL);
printf("i = %d\n", i);
}
return 0;
}
Can somebody explain why my assumption is incorrect?
Processes are not threads! When you fork, you create a full cloned process, with independant memory allocation that simply contains same values (except for the result of the fork call) at the time of the fork.
If you want a child to update some data in the parent process, you will need to use a thread. A thread shares all static and dynamic allocated memory with its parent, and simply has independant automatic variables. But even there, you should use static allocation for
i
variable:When you
fork
the child process gets a copy of the address space of the parent address space, they don't share it, so when the child changedi
the parent won't see it.This copying of the address space it typically done using copy on write to avoid allocating memory that will never change.
Variables are not shared between processes. After the call to
fork
, there are two completely separate processes.fork
returns 0 in the child, where the local variable is set to 5. In the parent, wherefork
returns the process ID of the child, the value ofi
is not changed; it still has the value 0 set beforefork
was called. It's the same behavior as if you had two programs run separately:and