Combining fork() and exec()
What you'll learn: How to launch a completely new program from within your own code without terminating the original process.
The "Cloning and Transforming" Strategy
In systems programming, we rarely use exec() by itself because it is "destructive"—it completely replaces your current program with a new one, meaning any code after the exec() call never runs. To start a new program while keeping our original one alive, we use a two-step pattern: Fork then Exec.
Think of it like a cell dividing. First, the process uses fork() to create an identical twin (the child). Then, that twin immediately walks into a "transformation booth" (exec()) to become a different person (a new program). The original parent process remains outside the booth, alive and well, waiting for the twin to finish its work.
Putting it into Code
To do this, we check the return value of fork(). If we are in the child process, we call exec(). If we are in the parent, we usually call wait() to stay in sync.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
// Fork failed
return 1;
} else if (pid == 0) {
// We are the CHILD
printf("Child: I'm becoming the 'ls' command!\n");
char *args[] = {"ls", "-l", NULL};
execvp(args[0], args);
// This line only runs if exec fails
perror("exec failed");
} else {
// We are the PARENT
printf("Parent: I'm waiting for my child to finish.\n");
wait(NULL);
printf("Parent: Child is done. I'm still running!\n");
}
return 0;
}
Why This Matters
This is exactly how a Terminal (like Bash or Zsh) works. When you type ls or mkdir, the shell doesn't become that command; it forks a child. The child transforms into the command you requested, executes it, and exits. Meanwhile, the parent shell stays active, waiting for the child to finish so it can show you the prompt again. By combining these two system calls, your program gains the power to manage multiple independent tasks simultaneously.
Key takeaway
Use fork() to create a workspace and exec() to fill that workspace with a new program, allowing your original process to continue managing the system.