CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 2 min read

exec

In plain words: fork alone only makes copies of the same program. To run a different program, a process calls exec. The call loads a new program file into the calling process and starts it from the beginning. The PID stays the same, as do the open files, but the old code, data, heap and stack are replaced.

This has a consequence: if exec succeeds, it never returns, because the code that would receive the return value has been wiped out. If it returns at all, it failed. There are several variants, such as execvp, which searches the directories in the PATH variable and takes the arguments as an array ending in NULL.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
    pid_t pid = fork();
    if (pid == 0) {
        char *args[] = {"wc", "-l", "/etc/passwd", NULL};
        execvp("wc", args);
        perror("exec");
        _exit(127);
    }
    wait(NULL);
    printf("parent done\n");
    return 0;
}

Output:

57 /etc/passwd
parent done

The number 57 is the line count of the file on the test machine, the same as wc -l /etc/passwd gives. The child became wc. The parent waited, then printed. The lines after execvp run only when it fails. Running execvp("nosuchprog", ...) printed execvp: No such file or directory, which is the errno message (Level 0, page 2) for a missing program.

Why two calls instead of one call that "starts a program"? The gap between fork and exec lets the child change things before the new program runs: it can redirect its output, change directory or close files. The shell uses exactly that gap (page 4), and pipes use it as well (page 7). The parent is untouched by those changes, since they happen in the child's copy.

exec

exec is the family of system calls (execl, execvp, execve and others) that load a new program into the calling process. The old code, data, heap and stack are discarded and replaced, and execution starts at the beginning of the new program. The PID stays the same, most open files stay open, and a successful call never returns.

Example: execvp("ls", args) turns the calling process into ls, and the code after it runs only if ls could not be started.

Check yourself: 1. Does exec create a new process? 2. When does the line after execvp run? 3. What can a child do between fork and exec that is useful?