Replacing process images with execl()
What you'll learn: How to use the execl() function to transform your current running process into a completely different program.
The Body Snatcher of Programming
In systems programming, we often want a process to start doing something entirely new. Imagine you are reading a book, and suddenly, you snap your fingers: your body stays in the same chair, but your brain and the book are instantly replaced by a chef cooking in a kitchen. You are still the same "entity" to the world, but your internal logic has been completely overwritten.
This is exactly what execl() (part of the exec family) does to a process. When you call execl(), the operating system wipes the current program's memory—its code, variables, and stack—and loads a new executable in its place.
How to use execl()
The execl() function stands for "execute list." You provide the path to the program you want to run and a list of arguments.
#include <stdio.h>
#include <unistd.h>
int main() {
printf("I am the original program. About to transform...\n");
// Arguments: (Path, Arg0, Arg1, ..., NULL)
// Arg0 is usually the name of the program itself.
execl("/bin/ls", "ls", "-l", "/home", NULL);
// This line will NEVER run if execl is successful
printf("You will never see this message.\n");
return 0;
}
The "Point of No Return"
The most critical thing to understand about execl() is that it does not return. Unlike a normal function call, there is no "coming back" to your original code. Because your original code has been erased and replaced by the new program (in this case, the ls command), the original process effectively ends when the new program finishes.
If you see the code after an execl() call actually executing, it means the function failed (perhaps the file path was wrong). Otherwise, the new program takes over the process ID (PID) of the original and carries on until it exits.
This is why execl() is almost always used inside a child process after a fork(). You split the process in two, and then the child uses execl() to become something else, while the parent stays behind to manage things.
Key takeaway
execl() replaces the current process image with a new one; it is a one-way transformation where the old code ceases to exist.