typestar

Replacing the process with exec in C

exec never returns on success, because the process becomes the new program.

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int run(const char *program, char *const argv[]) {
    pid_t pid = fork();
    if (pid < 0) {
        return -1;
    }
    if (pid == 0) {
        execvp(program, argv);
        perror("execvp");
        _exit(127);
    }
    int status = 0;
    waitpid(pid, &status, 0);
    return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
}

int list_files(void) {
    char *args[] = {"ls", "-1", NULL};
    return run("ls", args);
}

How it works

  1. The argument list is NUL-terminated by a NULL pointer.
  2. execvp searches PATH; execv needs a full path.
  3. Any code after a successful exec is unreachable.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
413
Tokens
135
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 2 of 4 in Processes & signals, step 8 of 14 in Systems programming.

← Previous Next →