mesmerizingr
mesmerizingr

Reputation: 1447

Some part of fork() mechanism

Upon reading "Linux Kernel Development" I saw next statetement:

Traditionally, upon fork(), all resources owned by the parent are duplicated and the copy is given to the child.This approach is naive and inefficient in that it copies much data that might otherwise be shared.Worse still, if the new process were to immediately execute a new image, all that copying would go to waste

Why do fork() need to copy all parent's resources? Why we can't simply allot freshly new chunk of space for all resources needed by new process? Why is there neediness in copying? And the last query - if the new process were to immediately execute the new image, why would that copying go to waste?

Upvotes: 3

Views: 194

Answers (3)

Adi
Adi

Reputation: 731

In case when we are not executing a new image like in the cases where we use pipes then copying of all the parents resources is very important. When they implemented fork() it should be generic no matter how the programmer uses it.So copying parents resources makes sense.

Upvotes: 1

Claudi
Claudi

Reputation: 5416

Well, that inefficiency is not such inefficient. AFAIK, fork() performs a copy-on-write. This mechanism makes memory to be copied only if the child process attempts to write it. So, x won't be copied if the child process doesn't write to it, yet it can access the variable for reading. Writing attempts are normally detected by a piece of hardware called "Memory Management Unit".

On the other hand, there are applications in which it is very useful to inherit a status variable from a child process, so "cleaning" the memory space would not be useful in such case.

Upvotes: 3

cnicutar
cnicutar

Reputation: 182629

Why we can't simply allot freshly new chunk of space for all resources needed by new process

The semantics of forks(2) say that when you do it another process starts executing from that point. So if it starts executing, it will naturally have some expectations regarding declared variables, their values and so on. You need to copy everything* the parent had access to.

int x = 42;
fork();
if (parent)
    /* x == 42. */
else
    /* I can haz x ? */

if the new process were to immediately execute the new image, why would that copying go to waste

This copying is completely useless if the new process turns out not to need continue from that point. For example, if the new process simply wants to start executing a new program, it won't need any of those variables mentioned above.

Upvotes: 4

Related Questions