Course contentsShow
← C
Lesson 1080 of 1,21915. Systems ProgrammingFree lesson

The execve() family overview

The execve() family overview

What you'll learn: How to replace a running process with a completely new program using the execve system call.

The Body Snatcher

In systems programming, we often start a new process using fork(), which creates a duplicate of the parent. But a clone isn't very useful if it just runs the same code forever. To actually run a different program—like opening ls or grep—we use the execve family of functions.

Think of execve as a "body snatcher." When a process calls it, the process doesn't die, but its "soul" (the code it was running) is instantly wiped out and replaced by a new program. The Process ID (PID) stays the same, but the memory, variables, and instructions are overwritten by the new executable. It is a point of no return: once the new program starts, the old code is gone.

How it works in code

While there are several helper functions (like execl or execvp), they all eventually call the system call execve. It requires three things: the path to the program, an array of arguments, and an array of environment variables.

#include <unistd.h>
#include <stdio.h>

int main() {
    char *binaryPath = "/bin/ls";
    char *args[] = {binaryPath, "-lh", "/home", NULL};
    char *env[] = {NULL};

    printf("About to replace this process...\n");

    // The system call
    execve(binaryPath, args, env);

    // This line will NEVER execute if execve is successful
    perror("execve failed");
    return 1;
}

The "One-Way Trip" Rule

The most important thing to remember is that execve does not "return" like a normal function. Because the entire memory space of your program is replaced by the new one, there is no "old code" to return to.

If execve is successful, the current program is simply gone, and the new program starts at its own main(). If you see the code continuing after an execve call, it means the system call failed (perhaps the file didn't exist or permissions were denied). This is why we usually fork() first: the parent stays alive to keep managing the system, while the child transforms into the new task.

Key takeaway

execve replaces the current process's memory and code with a new program, keeping the same PID but starting execution from scratch.