joozek
joozek

Reputation: 2211

How is unnecessary copying prevented in fork-exec?

Today I attended a lecture about linux processes. The teacher stated that:

  1. after fork() returns, child process is ready to be executed
  2. because of Copy On Write mechanism, fork-exec sequence is guaranteed to prevent unnecessary copying of parent's memory

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.

  1. fork returns 0, so line 3 is skipped
  2. when 0 is stored in "i" child haven't yet exec'ed, so COW kicks in copying (unnecessarily) parent's memory.

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

Answers (2)

Ed Heal
Ed Heal

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

Chris Stratton
Chris Stratton

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

Related Questions