Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of the process fork creates being a copy of the parent?

Tags:

c++

c

fork

I know the answer to "why is it this way" is because the language was invented so, but it seems like a lot of wasted effort that fork() spawns a copy of the process that called it. Perhaps it is useful sometimes, but surely the majority of time someone wants to start a new process its not to be a duplicate of the calling one? Why does fork create an identical process and not an empty one or one defined by passing an argument?

From yolinux

The fork() system call will spawn a new child process which is an identical process to the parent except that has a new system process ID

In other words when is it useful to start with a copy of the parent process?

like image 961
Celeritas Avatar asked Sep 16 '14 18:09

Celeritas


1 Answers

One big advantage of having the parent process duplicated in the child is that it allows the parent program to make customizations to the child process' environment before executing it. For example, the parent might want to read the child process' stdout, in which case it needs to set up the pipes in order to allow it to read that before execing the new program.

It's also not as bad as it sounds, efficiency wise. The whole thing is implemented on Linux using copy-on-write semantics for the process' memory (except in the special cases noted in the man page):

Under Linux (and in most unices since version 7, parent of all unices alive now), fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables (which can be also copy-on-write), and to create a unique task structure for the child.

like image 58
FatalError Avatar answered Sep 29 '22 11:09

FatalError