Operating System Interview Questions · Question 10

What is the difference between fork() and exec()?

Interview preparation resource from Gate Smashers.

Interview-ready answer

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.

Understand it clearly

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.

Quick comparison
Basisfork()exec()
PurposeCreates a child processLoads a new program
Process countIncreases by oneDoes not create a process
MemoryCopy-on-write initiallyReplaces current process image
Process IDChild receives a new PIDNormally keeps the same PID