7

But when we first time we adding a new name,we have to call malloc to obtain >room for a new list of pointers. We copy the old environment list to this new area and store a pointer to the name=value string at the end of the list of pointers.But most of the pointers in this list still point to name=value strings above the top of the stack(said in the Advanced Programming in the UNIX Environment.).It sounds like that are there any new created environment lists or strings stored in the queue.

7

Environment variables are stored together with command line arguments at the top of the process memory layout, above the stack.

enter image description here

| improve this answer | |
6

The environment (name/value pairs) lives towards the top of the stack. Figure 2 and Section 3 of Startup state of a Linux/i386 ELF binary shows about where the environment is. That doc is somewhat out of date, as ELF auxiliary vector also lives on the stack.

You can check this with a small C program:

#include <stdio.h>
int main(int argc, char **argv, char **env)
{
        printf("argv holds %p\n", argv);
        printf("argv[0] holds %p\n", argv[0]);
        printf("env holds %p\n", env);
        printf("env[0] holds %p\n", env[0]);
        return 0;
}

That doesn't answer another similar question: when you do export SOME_VAR in a shell, where does that shell put the new environment variable? A shell must keep its environment in a data structure that can be expanded at will, and then (converted to an array and) used as the envp (3rd) argument in execve(2) system calls.

| improve this answer | |
3

Environment variables are a manifestation of the shell you're using. I would imagine that the environment as a whole is a data structure that is part a component of what makes up a process.

I wouldn't expect them to be kept together in any singular place for all processes, rather each process more likely keeps the environment variables together with a given process along with other information related to a given process.

You can kind of see this if you poke around the /proc filesystem which maintains information about processes as they run on your kernel.

Example

If we look up one of my bash processes:

$ ps -eaf| grep bash | tail -1
saml     12095  3211  0 May10 pts/53   00:00:04 bash

Looking at this processes /proc area (list the first 5):

$ sudo cat /proc/12095/environ | tr '\0' '\n' | head -5
rvm_log_path=/home/saml/.rvm/log
rvm_ruby_string=ruby-1.9.2-p180
TERM=xterm
SHLVL=1
KDEDIRS=/usr

This shows at least the initial environment that this process started out with. I believe the /proc/PID/environ does not reflect an active representation of this processes environment as it get's augmented.

| improve this answer | |

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.