What is the difference between fork() and exec()?
Interview preparation resource from Gate Smashers.
fork() creates a new child process, while exec() replaces the current process image with a new program. Shells commonly fork first and then call exec in the child.
After fork(), parent and child continue from the next instruction but receive different return values. The child gets a new process ID. Modern systems initially share physical pages using copy-on-write, so memory is copied only when one process modifies a shared page.
exec() does not normally create another process. It replaces the current code, data, heap and stack with a new executable while keeping the same process identity. If exec succeeds, it does not return to the old program.
The key distinction is that fork() preserves the current program image in a new process, whereas exec() replaces the caller's image. A command shell commonly forks, lets the child call exec() for the requested command, and keeps the parent shell available for the next command.
