Interview Q&A / Operating Systems

IntermediateQuick answer1 min readUpdated 3 Oct 2026

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

SHORT ANSWER

fork() creates a new process that is a copy of the caller. exec() replaces the current process's program with a new one, keeping the same PID. Shells combine them: fork a child, then exec the command in it.

Explain it simply

fork is photocopying a worker; exec is giving that worker a completely new job description. After fork you have two processes running the same program. After exec the same process runs a different program, and its old code, stack and heap are gone.

  • fork(): new PID, copy of the parent, both continue after the call.
  • exec() (a family: execl, execv, execvp and others): same PID, new program image. On success it never returns, since the code that called it no longer exists. It returns -1 only on failure.

Example

How a shell runs ls -l:

c
pid_t pid = fork();
if (pid == 0) {
    execlp("ls", "ls", "-l", NULL);  // child becomes the ls program
    perror("exec failed");           // reached only if exec failed
} else {
    wait(NULL);                      // shell waits for ls to finish
}

The shell forks so that it survives. If it called exec directly, the shell itself would be replaced by ls and vanish once ls ended. Open file descriptors normally survive exec, which is how redirection like ls > out.txt works: the child sets up its descriptors before calling exec.

What to say in the interview

"fork duplicates a process; exec replaces the running program inside a process. A shell forks a child and the child execs the command, so the shell stays alive. exec doesn't return on success."

Common mistakes

  • Thinking exec creates a new process. The PID stays the same.

#fork#exec#unix

Related questions

Practise more Operating Systems questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Operating Systems quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.