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

Passing arguments to execv()

Passing arguments to execv()

What you'll learn: How to properly format and pass an array of strings to a new process using the execv() system call.

The Suitcase of Arguments

When you use execv(), you aren't just telling the operating system to run a program; you are handing that program a "suitcase" of information. In C, this suitcase is an array of strings (pointers to characters).

Unlike other functions where you might pass arguments one by one, execv() requires them to be bundled together. Think of it like a relay race: you are handing a single baton to the next runner, and that baton contains all the instructions they need to start.

Formatting the Array

To use execv(), you must follow two strict rules when building your argument array:

  1. The first element (argv[0]) should traditionally be the name of the program itself.
  2. The last element must be NULL. This acts as a "stop sign" for the operating system so it knows there are no more arguments to read.

Here is how you set this up in code:

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

int main() {
    // The path to the executable we want to run
    char *path = "/bin/ls";

    // The argument array (the "suitcase")
    // index 0: The program name
    // index 1: A flag for the ls command
    // index 2: The NULL terminator
    char *args[] = {"ls", "-l", NULL};

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

    // execv takes the path and the array
    execv(path, args);

    // If execv works, this line is NEVER reached
    perror("execv failed");
    return 1;
}

Why the NULL matters

C arrays do not inherently know how long they are. If you forget to put NULL at the end of your args array, execv() will keep reading past your variables into random parts of your computer's memory. This usually leads to a crash or unpredictable behavior. By adding that final NULL, you are safely sealing the suitcase.

Once execv() is called successfully, the current process is wiped clean, and the new program starts fresh using the strings you provided in your array as its own argv.

Key takeaway

execv() requires a NULL-terminated array of strings where the first element is the program name.