A while ago I was exploring a simple C program's ELF binary using GDB. I saw that the environment variables that are printed when I run printenv in the terminal are also present at the top of the stack of the C program's binary that I ran in that terminal.

How does Bash actually execute a program and at the same time all the environment variables are also added onto the new process's stack? In short, what happens step by step when I run a program like this: ./myprogram


A Linux program is executed using the execve system call. execve has the following signature:

int execve(const char *filename, char *const argv[], char *const envp[]);

The last argument, envp, is used to pass the environment to the process, as an array of strings, each of the form key=value. By convention, the same environment is passed from one process to another, unless the calling process makes some changes to it. The kernel arranges for the new program to receive the environment on the stack, in the same manner the program arguments are passed.

The library functions execl, execlp, execv, and execvp do not take the envp parameter (but the execle and execvpe functions do). These functions take the environment from the global variable environ in the calling process. This way a program using the execle function to start another program does not have to worry about passing the environment, but the library function does it automatically "behind the scenes".

All the mentioned library functions eventually call the execve system call, passing the environment in theenvp parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.