Course contentsShow
← Linux
Lesson 13 of 1,8191. Shell Architecture and Process EnvironmentFree lesson

Execve and Environment Variable Inheritance

Control the flow of process attributes and memory spaces across executable boundaries.

In this lesson, you will learn how process memory is replaced during execution and how environment variables persist across that transition.

The Memory Overwrite

When a shell runs a command, it performs a fork() to create a new process. However, that child process is initially just a clone of the shell. To run a different program (like ls or grep), the process calls execve.

Think of execve as a "brain transplant." It wipes the current process's memory space clean, loads the new binary from the disk, and resets the instruction pointer to the beginning of the new program. Crucially, the process ID (PID) remains the same, but the original program is gone forever, replaced entirely by the new one.

The Environment Inheritance

Even though the program code is replaced, some things survive the "brain transplant." Specifically, the process’s environment variables—the key-value pairs stored in the process memory that hold data like PATH or USER—are passed down to the new program.

When the shell calls execve, it passes an array of these environment strings to the new program. Because the child process inherited these from the shell during the fork, the new program starts its life already knowing the configuration of your terminal session.

Consider this workflow:

  1. Shell: You set an environment variable: export MY_VAR="Hello"
  2. Fork: The shell creates a child. The child has MY_VAR="Hello" in its memory.
  3. Execve: The child calls execve("/bin/printenv", ...)
  4. Result: The printenv program starts, looks at its inherited environment, and prints MY_VAR=Hello.

This mechanism allows you to configure the behavior of programs (like changing the language of an application or the path where files are saved) without needing to modify the program’s source code. You are simply preparing the environment before the "transplant" occurs.

If you don't explicitly pass a new environment to execve, the new program will receive the exact copy of the environment that the parent process possessed at the moment of execution.

Key Takeaway: The execve system call replaces the program code in memory while preserving the process identity and carrying forward the parent's environment variables to the new executable.