Reputation: 2211
Today I attended a lecture about linux processes. The teacher stated that:
By fork-exec sequence I mean something like that:
if(!fork())
{
exec(...);
}
i = 0;
Which, as far as I know translates into this (written in pseudo-asm):
call fork
jz next
call exec(...)
next:
load 0
store i
Let's assume that parent has been granted enough CPU time to execute all the lines above in one run.
So how is unnecessary copying prevented in this case? It looks like it isn't, but I think linux developers were smart enough to do it ;)
Possible answer: child always runs first (parent is preemted after calling fork()) 1. Is that true? 2. If yes, does that guarantee prevention of unnecessary copying in all cases?
Upvotes: 1
Views: 171
Reputation: 60017
Basically two people can read the same book. But if one starts writing notes in the margin then the other person needs a copy of that page before that occurs. The person that has not written into the margin of the page does not want to see the other persons notes in the book.
Upvotes: 1
Reputation: 40397
The answer is essentially that necessary copying - of pages hosting any data which gets changed - happens, while unnecessary copying - of pages which have not been changed by either process since the fork - does not.
The latter would typically include not only unmodified data, but also those holding the program itself and shared libraries it has loaded - typically many pages that can be shared, vs. just a few which must be duplicated.
Once the child calls an exec function, the sharing (and any need for future copy-on-write) is terminated.
Upvotes: 0