Lesson 04intermediateProcesses

Program Execution with exec()

Replacing a process image with exec(): same PID, never returns on success, -1 and errno when it fails. The exec family (execl, execlp, execv, execvp, execle), the fork+exec pattern with a calculator, open files and environment across exec, and a tiny shell that runs your commands.

execexecvpfork-execerrnomini shell
1

exec Family Variants

Demonstrating execl, execlp, execv, and execvp — the four main ways to call exec with different argument styles.

basic_exec.c
/*
 * basic_exec.c — exec family — execl, execlp, execv, execvp variants
 *
 * Key concepts: exec replaces process image, 'l' vs 'v', 'p' for PATH search
 * Compile: gcc -o exec basic_exec.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>


int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  exec family\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    const int EXAMPLE = 1;

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(1);
    }

    if (pid == 0)
    {
        printf("[Child  PID %d] About to call exec — this process image will be REPLACED.\n\n", getpid());
        int status;
        switch (EXAMPLE)
        {
        case 1:
            printf("[Child] Using execl(\"/bin/ls\", \"ls\", \"-l\", NULL)\n");
            printf("        'l' = list arguments, no 'p' = full path required\n\n");
            status = execl("/bin/ls" ,"ls", "-l", NULL);
            break;
        case 2:
            printf("[Child] Using execv(\"/bin/ls\", args)\n");
            printf("        'v' = vector (char* array), no 'p' = full path required\n\n");
            char *args[] = {"ls", "-l", NULL};
            status = execv("/bin/ls", args);
            break;

        default:
            break;
        }
        if (status == -1) {
            perror("[Child] exec failed");
            exit(1);
        }

    }
    else {
        printf("[Parent PID %d] Created child PID %d. Waiting...\n", getpid(), pid);
        wait(NULL);
        printf("[Parent PID %d] Child finished. exec replaced its entire process image.\n\n", getpid());
    }

    return 0;
}
$ gcc -o basic_exec basic_exec.c
$ ./basic_exec
Expected Outputclick Run to execute live
══════════════════════════════════════
  exec family
══════════════════════════════════════


[Parent PID 1067] Created child PID 1068. Waiting...
[Child  PID 1068] About to call exec — this process image will be REPLACED.

[Child] Using execl("/bin/ls", "ls", "-l", NULL)
        'l' = list arguments, no 'p' = full path required

total 24
-rwxr-xr-x 1 cs11f46d55 students 18696 Nov 20 19:38 basic_exec
-rw-r--r-- 1 cs11f46d55 students  1918 Nov 20 19:38 basic_exec.c
[Parent PID 1067] Child finished. exec replaced its entire process image.
2

exec Replaces, It Doesn't Return

The PID printed before exec and by the new program after it is the same number: exec keeps the process and swaps the program. The printf after a successful exec never runs.

01-exec-replaces.c
/*
 * 01-exec-replaces.c — exec does not start a new process: it REPLACES the program in this one
 *
 * Key concepts: same PID before and after exec, exec never returns on success
 * Compile: gcc -o exec_replaces 01-exec-replaces.c
 * Run:     ./exec_replaces
 *
 * fork() makes a new process. exec() keeps the process (same PID, same open files)
 * but throws away its code and memory and loads another program instead.
 * So the printf after a successful exec can never run: that code is gone.
 */
#include <stdio.h>
#include <unistd.h>

int main(void)
{
    printf("[Before exec] I am PID %d, running 01-exec-replaces.c\n", getpid());
    fflush(stdout);                       // the buffer is thrown away by exec — flush first!

    // sh prints its own PID ($$): the same number, because it is the same process
    execl("/bin/sh", "sh", "-c", "echo \"[After exec]  I am PID $$, now running sh\"", (char *)NULL);

    printf("This line runs only if exec FAILED.\n");
    return 1;
}
$ gcc -o exec_replaces 01-exec-replaces.c
$ ./exec_replaces
Expected Outputclick Run to execute live
[Before exec] I am PID 1086, running 01-exec-replaces.c
[After exec]  I am PID 1086, now running sh
3

When exec Fails

exec returns only on failure: -1 with errno set. A missing program gives ENOENT, a file that is not executable (a .c source) gives EACCES — the child then exits 127, like the shell does.

02-exec-fails.c
/*
 * 02-exec-fails.c — exec returns only when it fails: always check it
 *
 * Key concepts: exec returns -1 and sets errno; ENOENT vs EACCES; perror(); exit after a failed exec
 * Compile: gcc -o exec_fails 02-exec-fails.c
 * Run:     ./exec_fails
 *
 * Two classic mistakes: a program that does not exist (ENOENT), and a file that exists
 * but is not executable — like a .c source file (EACCES).
 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

static void try_exec(const char *path)
{
    fflush(stdout);                       // flush before fork, or the child prints our text again (Lesson 02)
    pid_t pid = fork();
    if (pid == 0) {
        execl(path, path, (char *)NULL);
        // Only reached if exec failed:
        printf("  exec(\"%s\") failed: errno=%d (%s)\n", path, errno, strerror(errno));
        exit(127);                        // like the shell: 127 = could not run the command
    }
    int status;
    waitpid(pid, &status, 0);
    printf("  child exit status: %d\n\n", WEXITSTATUS(status));
}

int main(void)
{
    printf("1) A program that does not exist:\n");
    try_exec("./no_such_program");

    printf("2) A file that exists but is not executable (our own source file):\n");
    try_exec("./02-exec-fails.c");

    return EXIT_SUCCESS;
}
$ gcc -o exec_fails 02-exec-fails.c
$ ./exec_fails
Expected Outputclick Run to execute live
1) A program that does not exist:
  exec("./no_such_program") failed: errno=2 (No such file or directory)
  child exit status: 127

2) A file that exists but is not executable (our own source file):
  exec("./02-exec-fails.c") failed: errno=13 (Permission denied)
  child exit status: 127
4

Calculator (Child Program)

A standalone calculator that reads operands and an operator from argv — designed to be launched via exec.

calculator.c
/*
 * calculator.c — Calculator child program (used by calculator_exec.c)
 *
 * Key concepts: This is the child program that exec launches
 * Compile: gcc -o calculator calculator.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>    // for getpid()

int main(int argc, char *argv[]) {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Calculator child program (used by calculator_exec.c)\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    printf("[Calculator PID %d] Launched by parent via exec().\n", getpid());
    printf("[Calculator] Received %d arguments (expected 3: num op num)\n\n", argc - 1);
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <num1> <operator> <num2>\n", argv[0]);
        return 1;
    }

    // Parse arguments
    int num1 = atoi(argv[1]);
    char operator = argv[2][0];
    int num2 = atoi(argv[3]);
    int result = 0;

    // Perform calculation based on the operator
    switch (operator) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 == 0) {
                fprintf(stderr, "Error: Division by zero\n");
                return 1;
            }
            result = num1 / num2;
            break;
        default:
            fprintf(stderr, "Error: Invalid operator '%c'\n", operator);
            return 1;
    }

    printf("[Calculator] %d %c %d = %d\n\n", num1, operator, num2, result);
    return 0;
}
$ gcc -o calculator calculator.c
$ ./calculator 6 + 7
Expected Outputclick Run to execute live
══════════════════════════════════════
  Calculator child program (used by calculator_exec.c)
══════════════════════════════════════


[Calculator PID 1136] Launched by parent via exec().
[Calculator] Received 3 arguments (expected 3: num op num)

[Calculator] 6 + 7 = 13
5

Calculator Launcher (Parent)

Parent program that forks a child and uses exec to launch the calculator program, passing arguments through argv. Run builds ./calculator first, because the child execs it.

calculator_exec.c
/*
 * calculator_exec.c — Parent program that fork+exec's the calculator
 *
 * Key concepts: fork+exec pattern, parent passes args to child via exec
 * Compile: gcc -o calc_exec calculator_exec.c
 * Run:     ./prog
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Parent program that fork+exec's the calculator\n");
    printf("══════════════════════════════════════\n\n");
    printf("\n");
    printf("[Parent PID %d] Will fork, then exec the calculator program.\n\n", getpid());
    const int EXAMPLE = 1;

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork failed");
        exit(1);
    }

    if (pid == 0) {
        printf("[Child  PID %d] Replacing myself with ./calculator via exec...\n", getpid());
        int status;

        switch (EXAMPLE) {
            case 1: {
                // Using execl: Pass arguments as separate strings
                status = execl("./calculator", "calculator", "5", "+", "3", NULL);
                break;
            }
            case 2: {
                // Using execv: Pass arguments as a char array
                char *args[] = {"calculator", "8", "*", "4", NULL};
                status = execv("./calculator", args);
                break;
            }
            default:
                fprintf(stderr, "Invalid EXAMPLE value\n");
                exit(1);
        }

        if (status == -1) {
            perror("exec failed");
            exit(1);
        }
    } else {
        // Parent process
        printf("[Parent PID %d] Waiting for child PID %d to complete...\n", getpid(), pid);
        wait(NULL);
        printf("[Parent PID %d] Child finished. The calculator ran in a separate process.\n\n", getpid());
    }

    return 0;
}
$ gcc -o calculator calculator.c && gcc -o calc_exec calculator_exec.c
$ ./calc_exec
Expected Outputclick Run to execute live
══════════════════════════════════════
  Parent program that fork+exec's the calculator
══════════════════════════════════════


[Parent PID 1162] Will fork, then exec the calculator program.

[Parent PID 1162] Waiting for child PID 1163 to complete...
[Child  PID 1163] Replacing myself with ./calculator via exec...

══════════════════════════════════════
  Calculator child program (used by calculator_exec.c)
══════════════════════════════════════


[Calculator PID 1163] Launched by parent via exec().
[Calculator] Received 3 arguments (expected 3: num op num)

[Calculator] 5 + 3 = 8

[Parent PID 1162] Child finished. The calculator ran in a separate process.
6

Choosing the Environment

execle() hands the new program an environment of your choice: `env` then prints only GREETING and COURSE — no HOME, no PATH.

03-exec-env.c
/*
 * 03-exec-env.c — The new program gets exactly the environment you pass it
 *
 * Key concepts: environment variables, execle(), getenv(), the env command
 * Compile: gcc -o exec_env 03-exec-env.c
 * Run:     ./exec_env
 *
 * Normally exec passes your environment along unchanged. The 'e' variants (execle, execve)
 * let you hand over a different one — here a tiny environment with just two variables.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    printf("[Parent] my HOME is %s and my USER is %s\n\n", getenv("HOME"), getenv("USER"));
    fflush(stdout);

    pid_t pid = fork();
    if (pid == 0) {
        char *small_env[] = { "GREETING=hello from the parent", "COURSE=OS", NULL };
        printf("[Child] exec'ing `env` with only two variables:\n");
        fflush(stdout);
        execle("/usr/bin/env", "env", (char *)NULL, small_env);
        perror("execle");
        exit(127);
    }
    wait(NULL);
    printf("\n[Parent] env printed only GREETING and COURSE — no HOME, no PATH.\n");
    return EXIT_SUCCESS;
}
$ gcc -o exec_env 03-exec-env.c
$ ./exec_env
Expected Outputclick Run to execute live
[Parent] my HOME is /work/e8c25c44 and my USER is student

[Child] exec'ing `env` with only two variables:
GREETING=hello from the parent
COURSE=OS

[Parent] env printed only GREETING and COURSE — no HOME, no PATH.
7

Open Files Survive exec

The child points stdout at listing.txt with dup2(), then execs `ls -l`. ls just writes to stdout — the listing lands in the file (see the Files panel). This is how `ls -l > listing.txt` works.

04-exec-redirect.c
/*
 * 04-exec-redirect.c — Open files survive exec: this is how `ls -l > listing.txt` works
 *
 * Key concepts: file descriptors are kept across exec, open(), dup2(), fork + exec
 * Compile: gcc -o exec_redirect 04-exec-redirect.c
 * Run:     ./exec_redirect       (then open listing.txt in the Files panel)
 *
 * The child opens listing.txt and puts it in place of stdout (file descriptor 1) with dup2().
 * Then it execs `ls -l`. ls has no idea about the file — it just writes to stdout,
 * and stdout is still listing.txt, because exec keeps open file descriptors.
 * (dup2 comes back in depth in Lesson 08.)
 */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {
        int fd = open("listing.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
        if (fd == -1) {
            perror("listing.txt");
            exit(1);
        }
        dup2(fd, STDOUT_FILENO);          // stdout (fd 1) now refers to listing.txt
        close(fd);
        execlp("ls", "ls", "-l", (char *)NULL);
        perror("execlp");                 // stderr still goes to the terminal
        exit(127);
    }

    int status;
    waitpid(pid, &status, 0);
    printf("[Parent] ls exited with status %d; its output is in listing.txt, not here.\n", WEXITSTATUS(status));
    return EXIT_SUCCESS;
}
$ gcc -o exec_redirect 04-exec-redirect.c
$ ./exec_redirect
Expected Outputclick Run to execute live
[Parent] ls exited with status 0; its output is in listing.txt, not here.
8

A Tiny Shell

Read a command, split it into an argv array, fork + execvp + waitpid, and report how it ended — what bash does for every command. A missing command exits 127.

05-mini-shell.c
/*
 * 05-mini-shell.c — A tiny shell: read a command, fork, exec it, wait, report how it ended
 *
 * Key concepts: fgets + strtok into an argv array, fork + execvp + waitpid, exit status
 * Compile: gcc -o mini_shell 05-mini-shell.c
 * Run:     ./mini_shell      (try: echo hello · ls -l · wc -l 05-mini-shell.c · nosuchcmd · exit)
 *
 * This is exactly what bash does for every command you type — minus pipes, redirection,
 * quotes and the rest. execvp searches PATH, so "ls" works without "/bin/ls".
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAX_ARGS 32

int main(void)
{
    char line[256];

    for (;;) {
        printf("mini$ ");
        fflush(stdout);
        if (fgets(line, sizeof line, stdin) == NULL)   // Ctrl+D (end of input) ends the shell
            break;

        // Split the line into words: "wc -l file" -> {"wc", "-l", "file", NULL}
        char *argv[MAX_ARGS];
        int argc = 0;
        for (char *w = strtok(line, " \t\n"); w && argc < MAX_ARGS - 1; w = strtok(NULL, " \t\n"))
            argv[argc++] = w;
        argv[argc] = NULL;
        if (argc == 0)
            continue;                                    // empty line
        if (strcmp(argv[0], "exit") == 0)
            break;

        pid_t pid = fork();
        if (pid == -1) {
            perror("fork");
            continue;
        }
        if (pid == 0) {
            execvp(argv[0], argv);
            fprintf(stderr, "mini: %s: command not found\n", argv[0]);
            exit(127);
        }

        int status;
        waitpid(pid, &status, 0);
        if (WIFEXITED(status))
            printf("[mini] %s exited with status %d\n", argv[0], WEXITSTATUS(status));
        else if (WIFSIGNALED(status))
            printf("[mini] %s killed by signal %d\n", argv[0], WTERMSIG(status));
    }
    printf("bye\n");
    return EXIT_SUCCESS;
}
$ gcc -o mini_shell 05-mini-shell.c
$ ./mini_shell
Expected Outputclick Run to execute live
mini$ echo hello
ls -l
wc -l 05-mini-shell.c
nosuchcmd
exit
hello
[mini] echo exited with status 0
mini$ total 24
-rw-r--r-- 1 cs5fb963d2 students  1924 Nov 20 19:38 05-mini-shell.c
-rwxr-xr-x 1 cs5fb963d2 students 18928 Nov 20 19:38 mini_shell
[mini] ls exited with status 0
mini$ 60 05-mini-shell.c
[mini] wc exited with status 0
mini$ mini: nosuchcmd: command not found
[mini] nosuchcmd exited with status 127
mini$ bye
Asks for input — sample input is one click away
9

Binary Search Utility

A binary search implementation that handles duplicates — a review exercise combining C fundamentals with algorithms.

binary_search_dupes.c
$ gcc -o bsearch binary_search_dupes.c
$ ./bsearch
Expected Outputclick Run to execute live
══════════════════════════════════════
  Binary search with duplicate handling (utility/review)
══════════════════════════════════════


  Worst case: O(n) if all elements are the same.

  Test   | Array                        | Target   | Got      | Expected
  ------ | ---------------------------- | -------- | -------- | --------
  #1     | {1,2,2,2,3,4,5}             | 2        | 3        | 3  OK
  #2     | {1,1,1,1,1,1}               | 1        | 6        | 6  OK
  #3     | {1,2,3,4,5,6,7}             | 5        | 1        | 1  OK
  #4     | {1,3,3,3,5,5,5,7}           | 3        | 3        | 3  OK
  #5     | {1,2,3,4,5}                 | 10       | 0        | 0  OK

========================================

Open Full Terminal

Get a Linux terminal with all 9 files from this lesson pre-loaded. Compile, run, and experiment freely.