The Linux Programming Interface

(nextflipdebug5) #1
Processes 125

6.7 Environment List


Each process has an associated array of strings called the environment list, or simply
the environment. Each of these strings is a definition of the form name=value. Thus, the
environment represents a set of name-value pairs that can be used to hold arbitrary
information. The names in the list are referred to as environment variables.
When a new process is created, it inherits a copy of its parent’s environment.
This is a primitive but frequently used form of interprocess communication—the
environment provides a way to transfer information from a parent process to its
child(ren). Since the child gets a copy of its parent’s environment at the time it is
created, this transfer of information is one-way and once-only. After the child pro-
cess has been created, either process may change its own environment, and these
changes are not seen by the other process.
A common use of environment variables is in the shell. By placing values in its
own environment, the shell can ensure that these values are passed to the processes
that it creates to execute user commands. For example, the environment variable
SHELL is set to be the pathname of the shell program itself. Many programs interpret
this variable as the name of the shell that should be executed if the program needs
to execute a shell.
Some library functions allow their behavior to be modified by setting environ-
ment variables. This allows the user to control the behavior of an application using
the function without needing to change the code of the application or relink it
against the corresponding library. An example of this technique is provided by the
getopt() function (Appendix B), whose behavior can be modified by setting the
POSIXLY_CORRECT environment variable.
In most shells, a value can be added to the environment using the export command:

$ SHELL=/bin/bash Create a shell variable
$ export SHELL Put variable into shell process’s environment

In bash and the Korn shell, this can be abbreviated to:

$ export SHELL=/bin/bash

In the C shell, the setenv command is used instead:

% setenv SHELL /bin/bash

The above commands permanently add a value to the shell’s environment, and this
environment is then inherited by all child processes that the shell creates. At any
point, an environment variable can be removed with the unset command (unsetenv
in the C shell).
In the Bourne shell and its descendants (e.g., bash and the Korn shell), the fol-
lowing syntax can be used to add values to the environment used to execute a sin-
gle program, without affecting the parent shell (and subsequent commands):

$ NAME=value program

This adds a definition to the environment of just the child process executing the
named program. If desired, multiple assignments (delimited by white space) can
precede the program name.
Free download pdf