Reputation: 513
I have the code:
int a = 0;
if (fork() == 0) {
a = a + 1;
printf("%d \n", a);
} else {
a = a - 1;
printf("%d \n", a);
}
And I want to know whether or not this code will always print different values for the 2 prints?
Or if we will have context switch after the son process will add 1 and then the father process will do minus 1. In this case we will get same value. The thing is I'm not sure if the variable 'a' is duplicated and each process will have different copy of it (and then we will always get different values), or is shared (and then the situation I mentions can cause the same value to be printed twice)?
Thanks a lot!
Upvotes: 2
Views: 2197
Reputation: 12679
The fork()
creates a child process by duplicating the calling process.
The process that invoked fork()
is the parent process and the newly created process is the child process. The child process and the parent process run in separate memory spaces. But at the time of fork()
both memory spaces have the same content.
There is concept called Copy-on-Write, which is an optimization where the page tables are set up so that the parent and child process start off sharing all of the same memory, and only the pages that are written to by either process are copied when needed. Which means both parent and child process share copy of the same data and as soon as either of them do a write, a copy is made and any change in the memory of one process is not visible in another's.
In the context of your program -
Yes, both parent and child process share a copy of variable a
until its written by either of the process and then a copy is made. Any change in value of variable a
done by either of the process (parent/child) will be in its own copy of a
and that change is not visible to the other process.
Check this - Copy-on-write.
Upvotes: 3
Reputation: 60143
A forked child doesn't share its address space with its parent. It gets a copy, although as an optimization, that copy may be a lazy, copy-on-write copy, which is what Linux does.
On Linux a forked child process will initially share its address space with its parent, but if it attempts to write anywhere, then (provided that write attempt is not a segmentation fault) Linux will redirect that write to a copy of the original page.
Upvotes: 3