So when a command is fired from a shell, fork() inherits a child
process of it and exec() loads the child process to the memory and
fork() clones the current process, creating an identical child.
exec() loads a new program into the current process, replacing the existing one.
My qs is:
If the child process contains all the attributes of the parent process(which is the original process), then what is the need of this
child process? The original process also could have been loaded to the
The need is because the parent process does not want to terminate yet; it wants a new process to go off and do something at the same time that it continues to execute as well.
Does this fork and exec concept apply to all the executable program in
UNIX?Like for shell script also or only for commands? Does it also
apply for shell builtin commands?
For external commands, the shell does a
fork() so that the command runs in a new process. Builtins are just run by the shell directly. Another notable command is
exec, which tells the shell to
exec() the external program without first
fork()ing. This means that the shell itself is replaced with the new program, and so is no longer there for that program to return to when it exits. If you say,
exec true, then
/bin/true will replace your shell, and immediately exit, leaving nothing running in your terminal anymore, so it will close.
when copy on write concept is used if I'll execute a command/script?
Back in the stone age,
fork() actually had to copy all of the memory in the calling process to the new process. Copy on Write is an optimization where the page tables are set up so that the two processes start off sharing all of the same memory, and only the pages that are written to by either process are copied when needed.