CodeBlanks Logo Icon CodeBlanks

exec

Learn to replace a process with the exec family.

The exec family

The exec family replaces the process memory with a new program. The process ID stays the same but code, data and stack are replaced. On success, exec does not return.

Common members: execl, execv, execlp, execvp. execvp searches the PATH variable; you just give the command name. For example, execvp("echo", args) replaces the process with echo. On failure it returns -1.

Why exec with fork?

Since exec replaces the process, calling it alone loses the original program. So you typically fork a child, call exec in the child, and the parent continues its own work.

This fork-exec pattern is the standard way to run programs in UNIX. Shells do this for every command: fork → child exec → parent wait. The shell keeps running while the child executes the command.

Practice Run echo with execvp

Define the array char *args[] = {"echo", "merhaba", NULL};. Replace the process with execvp("echo", args);. On failure print printf("exec failed\n");.

Starter code

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

// Define args array
// Call execvp
// Print on failure

int main(void) {
    return 0;
}

Sample solution

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

int main(void) {
    char *args[] = {"echo", "merhaba", NULL};
    execvp("echo", args);
    printf("exec failed\n");
    return 1;
}

Expected output

merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match exec members

Term Meaning
execl List form
execv Array form
execlp PATH search list
execvp PATH search array

2 What happens when execvp succeeds?

  • The process terminates
  • A new process is created
  • The PID changes
  • The process program changes Correct answer

Explanation: exec replaces the process program; the PID stays.

3 args array

Question
char *args[] = {"echo", "merhaba", ____};
Answer
char *args[] = {"echo", "merhaba", NULL};

Explanation: The args array must end with NULL.

All lessons in Advanced